namespace ThreadPilot.Services { using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Windows.Input; using System.Windows.Interop; using Microsoft.Extensions.Logging; public class KeyboardShortcutService : IKeyboardShortcutService, IDisposable { private readonly ILogger logger; private readonly IApplicationSettingsService settingsService; private readonly Dictionary registeredShortcuts = new(); private readonly Dictionary hotkeyIdToAction = new(); private int nextHotkeyId = 1; private IntPtr windowHandle = IntPtr.Zero; private HwndSource? hwndSource; private bool disposed; // Windows API constants private const int WMHOTKEY = 0x0312; private const int MODALT = 0x0001; private const int MODCONTROL = 0x0002; private const int MODSHIFT = 0x0004; private const int MODWIN = 0x0008; // Windows API functions [DllImport("user32.dll")] private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk); [DllImport("user32.dll")] private static extern bool UnregisterHotKey(IntPtr hWnd, int id); public event EventHandler? ShortcutActivated; public KeyboardShortcutService( ILogger logger, IApplicationSettingsService settingsService) { this.logger = logger; this.settingsService = settingsService; } public async Task RegisterShortcutAsync(string actionName, Key key, ModifierKeys modifiers) { try { if (string.IsNullOrEmpty(actionName)) { return false; } if (this.windowHandle == IntPtr.Zero) { this.logger.LogWarning( "Skipped registering shortcut for action {Action} because no window handle is available yet", actionName); return false; } // Check if shortcut is already registered if (await this.IsShortcutRegisteredAsync(key, modifiers)) { this.logger.LogWarning("Shortcut {Key}+{Modifiers} is already registered", key, modifiers); return false; } // Unregister existing shortcut for this action if it exists if (this.registeredShortcuts.ContainsKey(actionName)) { await this.UnregisterShortcutAsync(actionName); } var shortcut = new KeyboardShortcut { ActionName = actionName, Key = key, Modifiers = modifiers, Description = this.GetActionDescription(actionName), IsEnabled = true, IsGlobal = true, }; // Register with Windows API var hotkeyId = this.nextHotkeyId++; var winModifiers = this.ConvertToWinModifiers(modifiers); var virtualKey = KeyInterop.VirtualKeyFromKey(key); if (RegisterHotKey(this.windowHandle, hotkeyId, winModifiers, (uint)virtualKey)) { this.registeredShortcuts[actionName] = shortcut; this.hotkeyIdToAction[hotkeyId] = actionName; this.logger.LogInformation( "Registered global shortcut {Shortcut} for action {Action}", shortcut.ToString(), actionName); return true; } else { this.logger.LogError( "Failed to register global shortcut {Shortcut} for action {Action}", shortcut.ToString(), actionName); return false; } } catch (Exception ex) { this.logger.LogError(ex, "Error registering shortcut for action {Action}", actionName); return false; } } public Task UnregisterShortcutAsync(string actionName) => Task.FromResult(this.UnregisterShortcut(actionName)); private bool UnregisterShortcut(string actionName) { try { if (!this.registeredShortcuts.TryGetValue(actionName, out var shortcut)) { return false; } // Find the hotkey ID var hotkeyId = this.hotkeyIdToAction.FirstOrDefault(kvp => kvp.Value == actionName).Key; if (hotkeyId == 0) { return false; } // Unregister from Windows API var unregistered = UnregisterHotKey(this.windowHandle, hotkeyId); this.registeredShortcuts.Remove(actionName); this.hotkeyIdToAction.Remove(hotkeyId); if (unregistered) { this.logger.LogInformation( "Unregistered shortcut {Shortcut} for action {Action}", shortcut.ToString(), actionName); return true; } this.logger.LogError( "Failed to unregister shortcut {Shortcut} for action {Action}", shortcut.ToString(), actionName); return false; } catch (Exception ex) { this.logger.LogError(ex, "Error unregistering shortcut for action {Action}", actionName); return false; } } public async Task UpdateShortcutAsync(string actionName, Key key, ModifierKeys modifiers) { // Unregister existing shortcut and register new one await this.UnregisterShortcutAsync(actionName); return await this.RegisterShortcutAsync(actionName, key, modifiers); } public async Task> GetRegisteredShortcutsAsync() { return new Dictionary(this.registeredShortcuts); } public async Task IsShortcutRegisteredAsync(Key key, ModifierKeys modifiers) { return this.registeredShortcuts.Values.Any(s => s.Key == key && s.Modifiers == modifiers); } public async Task LoadShortcutsFromSettingsAsync() { try { var configuredShortcuts = this.settingsService.Settings.KeyboardShortcuts; if (configuredShortcuts != null && configuredShortcuts.Count > 0) { foreach (var shortcutSetting in configuredShortcuts) { if (shortcutSetting.IsEnabled) { await this.RegisterShortcutAsync(shortcutSetting.ActionName, shortcutSetting.Key, shortcutSetting.Modifiers); } } } else { // Load default shortcuts if none are configured await this.LoadDefaultShortcutsAsync(); } this.logger.LogInformation("Loaded {Count} keyboard shortcuts from settings", this.registeredShortcuts.Count); } catch (Exception ex) { this.logger.LogError(ex, "Error loading shortcuts from settings"); } } public async Task SaveShortcutsToSettingsAsync() { try { var settings = this.settingsService.Settings; settings.KeyboardShortcuts = this.registeredShortcuts.Values.ToList(); await this.settingsService.UpdateSettingsAsync(settings); this.logger.LogInformation("Saved {Count} keyboard shortcuts to settings", this.registeredShortcuts.Count); } catch (Exception ex) { this.logger.LogError(ex, "Error saving shortcuts to settings"); } } public Task ClearAllShortcutsAsync() { this.ClearAllShortcuts(); return Task.CompletedTask; } private void ClearAllShortcuts() { foreach (var action in this.registeredShortcuts.Keys.ToList()) { this.UnregisterShortcut(action); } } public Dictionary GetDefaultShortcuts() { return new Dictionary { [ShortcutActions.ShowMainWindow] = new KeyboardShortcut { ActionName = ShortcutActions.ShowMainWindow, Key = Key.T, Modifiers = ModifierKeys.Control | ModifierKeys.Shift, Description = "Show/Hide main window", IsEnabled = true, IsGlobal = true, }, [ShortcutActions.ToggleMonitoring] = new KeyboardShortcut { ActionName = ShortcutActions.ToggleMonitoring, Key = Key.M, Modifiers = ModifierKeys.Control | ModifierKeys.Shift, Description = "Toggle process monitoring", IsEnabled = true, IsGlobal = true, }, [ShortcutActions.PowerPlanHighPerformance] = new KeyboardShortcut { ActionName = ShortcutActions.PowerPlanHighPerformance, Key = Key.H, Modifiers = ModifierKeys.Control | ModifierKeys.Shift, Description = "Switch to High Performance power plan", IsEnabled = true, IsGlobal = true, }, [ShortcutActions.OpenTweaks] = new KeyboardShortcut { ActionName = ShortcutActions.OpenTweaks, Key = Key.W, Modifiers = ModifierKeys.Control | ModifierKeys.Shift, Description = "Open System Tweaks tab", IsEnabled = true, IsGlobal = true }, }; } public void SetWindowHandle(IntPtr windowHandle) { if (this.windowHandle == windowHandle && this.hwndSource != null) { return; } if (this.hwndSource != null) { this.hwndSource.RemoveHook(this.WndProc); this.hwndSource = null; } this.windowHandle = windowHandle; // Set up message hook for hotkey messages if (this.windowHandle != nint.Zero) { this.hwndSource = HwndSource.FromHwnd(this.windowHandle); if (this.hwndSource != null) { this.hwndSource.AddHook(this.WndProc); } } } private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == WMHOTKEY) { var hotkeyId = wParam.ToInt32(); if (this.hotkeyIdToAction.TryGetValue(hotkeyId, out var actionName) && this.registeredShortcuts.TryGetValue(actionName, out var shortcut)) { this.ShortcutActivated?.Invoke(this, new ShortcutActivatedEventArgs(actionName, shortcut)); handled = true; } } return IntPtr.Zero; } private async Task LoadDefaultShortcutsAsync() { var defaultShortcuts = this.GetDefaultShortcuts(); foreach (var shortcut in defaultShortcuts.Values) { await this.RegisterShortcutAsync(shortcut.ActionName, shortcut.Key, shortcut.Modifiers); } } private uint ConvertToWinModifiers(ModifierKeys modifiers) { uint winModifiers = 0; if (modifiers.HasFlag(ModifierKeys.Alt)) { winModifiers |= MODALT; } if (modifiers.HasFlag(ModifierKeys.Control)) { winModifiers |= MODCONTROL; } if (modifiers.HasFlag(ModifierKeys.Shift)) { winModifiers |= MODSHIFT; } if (modifiers.HasFlag(ModifierKeys.Windows)) { winModifiers |= MODWIN; } return winModifiers; } private string GetActionDescription(string actionName) { return actionName switch { ShortcutActions.QuickApply => "Quick apply current settings", ShortcutActions.ToggleMonitoring => "Toggle process monitoring", ShortcutActions.ShowMainWindow => "Show/Hide main window", ShortcutActions.HideToTray => "Hide to system tray", ShortcutActions.PowerPlanBalanced => "Switch to Balanced power plan", ShortcutActions.PowerPlanHighPerformance => "Switch to High Performance power plan", ShortcutActions.PowerPlanPowerSaver => "Switch to Power Saver power plan", ShortcutActions.RefreshProcessList => "Refresh process list", ShortcutActions.OpenSettings => "Open Settings tab", ShortcutActions.OpenTweaks => "Open System Tweaks tab", ShortcutActions.ExitApplication => "Exit application", _ => actionName, }; } public void Dispose() { if (this.disposed) { return; } this.disposed = true; this.ClearAllShortcuts(); if (this.hwndSource != null) { this.hwndSource.RemoveHook(this.WndProc); this.hwndSource = null; } } } }