/// <summary> /// Register the hotkey with a Windows control /// </summary> /// <param name="windowControl"></param> /// <returns></returns> public bool Register(Control windowControl) { // Check that we have not registered if (this.isRegistered) { throw new NotSupportedException("You cannot register a hotkey that is already registered"); } // We can't register an empty hotkey if (this.IsEmpty) { throw new NotSupportedException("You cannot register an empty hotkey"); } // Get an ID for the hotkey and increase current ID this.id = Hotkey2.currentID; Hotkey2.currentID = (Hotkey2.currentID + 1) % Hotkey2.maximumID; // Translate modifier keys into unmanaged version uint modifiers = (this.Alt ? Hotkey2.MOD_ALT : 0) | (this.Control ? Hotkey2.MOD_CONTROL : 0) | (this.Shift ? Hotkey2.MOD_SHIFT : 0) | (this.Windows ? Hotkey2.MOD_WIN : 0); // Register the hotkey if (Hotkey2.RegisterHotKey(windowControl.Handle, this.id, modifiers, 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.isRegistered = true; this.windowControl = windowControl; // We successfully registered return(true); }
/// <summary> /// Unregister the hotkey /// </summary> public void Unregister() { // Check that we have registered if (!this.isRegistered) { throw new NotSupportedException("You cannot unregister a hotkey that is not registered"); } // 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 (Hotkey2.UnregisterHotKey(this.windowControl.Handle, this.id) == 0) { throw new Win32Exception(); } } // Clear the control reference and register state this.isRegistered = false; this.windowControl = null; }
public void RegisterAppHotKey() { INIFile root = Config.IniFile; this.userHotkey = new Hotkey2(Hotkey2.KeyCodeFromString(Config.KeyCode), Config.ShiftKey, Config.ControlKey, Config.AltKey, Config.WindowsKey); // Catch the 'Pressed' event this.userHotkey.Pressed += delegate(object sender1, HandledEventArgs ee) { this.ShowMainForm(); }; this.userHotkey.Register(this); if (this.userHotkey.GetCanRegister(this)) { MessageBox.Show("register hotkey fail!"); } /* Hotkey2 hk = new Hotkey2(Keys.A, false, true, false, true); hk.Register(this); if (hk.GetCanRegister(this)) { MessageBox.Show("register hotkey fail!"); } hk.Pressed+= delegate(object sender1, HandledEventArgs ee) { this.ShowMainForm(); };*/ }