public static void Register(KeyboardShortcutAction action) { if (RegisteredActions.ContainsKey(action.Id)) { Unregister(action.Id); } var win32Key = KeyInterop.VirtualKeyFromKey(action.Shortcut.Key); // Modifier keys codes: Alt = 1, Ctrl = 2, Shift = 4, Win = 8 // Compute the addition of each combination of the keys you want to be pressed // ALT+CTRL = 1 + 2 = 3 , CTRL+SHIFT = 2 + 4 = 6... if (!RegisterHotKey(App.Handler, action.Id, action.Modifiers(), (int)win32Key)) { MessageBox.Show($"Cannot use hotkey {action.Shortcut.ToString()}, probably windows or other application is using it."); } RegisteredActions[action.Id] = action; }
private static IntPtr KeyboardHookHandler(int nCode, IntPtr wParam, ref KBHookStruct lParam) { if (nCode == 0) { var wpfKey = KeyInterop.KeyFromVirtualKey(lParam.vkCode); var wparamTyped = wParam.ToInt32(); if (Enum.IsDefined(typeof(KeyboardState), wparamTyped)) { var isKeyDown = false; if (wparamTyped == (int)KeyboardState.WM_KEYDOWN || wparamTyped == (int)KeyboardState.WM_SYSKEYDOWN) { isKeyDown = true; if (!CurrentlyPressedKeys.Contains(wpfKey)) { CurrentlyPressedKeys.Add(wpfKey); } } else if (CurrentlyPressedKeys.Contains(wpfKey)) { CurrentlyPressedKeys.Remove(wpfKey); } else { var aaa = wparamTyped; } var key = new KeyboardShortcut(wpfKey) { CtrlModifier = CurrentlyPressedKeys.Contains(Key.LeftCtrl) || CurrentlyPressedKeys.Contains(Key.LeftCtrl), ShiftModifier = CurrentlyPressedKeys.Contains(Key.LeftShift) || CurrentlyPressedKeys.Contains(Key.RightShift), AltModifier = CurrentlyPressedKeys.Contains(Key.LeftAlt) || CurrentlyPressedKeys.Contains(Key.RightAlt), WinModifier = CurrentlyPressedKeys.Contains(Key.LWin) || CurrentlyPressedKeys.Contains(Key.RWin) }; var keyEvent = new KeyEvent(key); if (HandlerControls != null) { foreach (var control in HandlerControls) { if (control.CanHandleHook) { control.HandleHook(keyEvent); if (keyEvent.Handled) { break; } } } } if (keyEvent.Handled) { return(new IntPtr(1)); } else if (!keyEvent.Handled && isKeyDown) { KeyboardShortcutAction action = HotKeyManager.CallActionIfRegistered(key); if (action != null) { return(new IntPtr(1)); } } } } return(CallNextHookEx(CurrentHook, nCode, wParam, ref lParam)); }