public bool Register(Control windowControl) { // Check that we have not registered if (this.registered) { return(false); } //{ throw new NotSupportedException("You cannot register a hotkey that is already registered"); } // We can't register an empty hotkey if (this.Empty) { return(false); } // { throw new NotSupportedException("You cannot register an empty hotkey"); } // Get an ID for the hotkey and increase current ID this.id = GlobalHotkey.currentID; GlobalHotkey.currentID = GlobalHotkey.currentID + 1 % GlobalHotkey.maximumID; // Translate modifier keys into unmanaged version uint modifiers = (this.Alt ? GlobalHotkey.MOD_ALT : 0) | (this.Control ? GlobalHotkey.MOD_CONTROL : 0) | (this.Shift ? GlobalHotkey.MOD_SHIFT : 0) | (this.Windows ? GlobalHotkey.MOD_WIN : 0); // Register the hotkey if (GlobalHotkey.RegisterHotKey(windowControl.Handle, this.id, modifiers, hotkeyInfo.keyCode) == 0) { // Is the error that the hotkey is registered? if (Marshal.GetLastWin32Error() == ERROR_HOTKEY_ALREADY_REGISTERED) { return(false); } else { throw new Win32Exception(); } } // Save the control reference and register state this.registered = true; this.windowControl = windowControl; // We successfully registered return(true); }
public void Unregister() { // Check that we have registered if (!this.registered) { return; } // It's possible that the control itself has died: in that case, no need to unregister! if (!this.windowControl.IsDisposed) { // Clean up after ourselves if (GlobalHotkey.UnregisterHotKey(this.windowControl.Handle, this.id) == 0) { throw new Win32Exception(); } } // Clear the control reference and register state this.registered = false; this.windowControl = null; }