/// <summary> /// Registers the hotkey. /// </summary> /// <param name="modifier">Hotkey modifier.</param> /// <param name="key">Hotkey key.</param> private void RegisterGlobalHotkey(KeyModifier modifier, System.Windows.Forms.Keys key) { UnregisterGlobalHotkey(); try { // use the GlobalAddAtom API to get a unique ID (as suggested by MSDN) string atomName = Thread.CurrentThread.ManagedThreadId.ToString("X8") + this.GetType().FullName; ID = GlobalAddAtom(atomName); if (ID == 0) { throw new Exception("Unable to generate unique hotkey ID. Error: " + Marshal.GetLastWin32Error().ToString()); } // register the hotkey, throw if any error if (!RegisterHotKey(this.Helper.Handle, ID, (uint)modifier, (uint)key)) { throw new Exception("Unable to register hotkey. Error: " + Marshal.GetLastWin32Error().ToString()); } Key = key; Modifiers = modifier; GlobalHotkey.RegisterNewHotkey(this); } catch (Exception ex) { // clean up if hotkey registration failed Dispose(); Console.WriteLine(ex); } }
/// <summary> /// Registers a hotkey to the global message receiving queue. /// </summary> /// <param name="hotKey">Hot key to register.</param> internal static void RegisterNewHotkey(GlobalHotkey hotKey) { if (hotKey != null && hotKey.ID != 0) { _registeredHotkeys[hotKey.ID] = hotKey; } }
/// <summary> /// Unregisters this global key. /// </summary> private void UnregisterGlobalHotkey() { if (this.ID != 0) { GlobalHotkey.UnregisterHotkey(this); UnregisterHotKey(this.Helper.Handle, ID); // clean up the atom list GlobalDeleteAtom(ID); ID = 0; Key = System.Windows.Forms.Keys.None; Modifiers = KeyModifier.None; } }
/// <summary> /// Initializes a new instance of the HotkeyEventArgs class with a global hotkey. /// </summary> /// <param name="hotkey">Hotkey being the source of the event.</param> public HotkeyEventArgs(GlobalHotkey hotkey) { Hotkey = hotkey; }
/// <summary> /// Unregisters a hotkey from the message receiving queue. /// </summary> /// <param name="hotKey">Hotkey to unregister.</param> internal static void UnregisterHotkey(GlobalHotkey hotKey) { if (hotKey != null) { GlobalHotkey.UnregisterHotkey(hotKey.ID); } }