/// <summary> /// Hooks a system-wide hotkey. /// </summary> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="InvalidKeysValueException"></exception> public void Hook(HotkeyBinding hotkeyBinding) { CheckDisposed(); if (hotkeyBinding == null) throw new ArgumentNullException(nameof(hotkeyBinding)); var existingBinding = hotkeyBindings.FirstOrDefault(b => b.Hotkey == hotkeyBinding.Hotkey); if (existingBinding != null) { throw new HotkeyAlreadyBoundException( $@"The hotkey ""{hotkeyBinding.ToString("{0}")}"" is already hooked by this instance.", existingBinding, hotkeyBinding); } Keys keyCode = hotkeyBinding.Hotkey.GetKeyCode(); Modifiers mods = KeysToModifiers(hotkeyBinding.Hotkey); bool successful = NativeMethods.RegisterHotKey (bindingWindow.Handle, hotkeyBinding.Hotkey.GetHashCode(), (uint)mods, (uint)keyCode); if (!successful) { int errorCode = Marshal.GetLastWin32Error(); switch (errorCode) { case 1409: throw new HotkeyAlreadyBoundException( $@"The hotkey ""{hotkeyBinding.ToString("{0}")}"" is already hooked by another program."); default: throw new NotImplementedException("Unexpected Win32Error code."); } } hotkeyBindings.Add(hotkeyBinding); }
/// <summary> /// Determines whether the specified HotkeyBinding is equal to the current HotkeyBinding. /// </summary> /// <returns> /// true if the specified HotkeyBinding is equal to the current HotkeyBinding; otherwise, false. /// </returns> protected bool Equals(HotkeyBinding other) { return(Hotkey == other.Hotkey); }
/// <summary> /// Initializes a new instance of the <see cref="HotkeyAlreadyBoundException"/> class /// with the specified arguments. /// </summary> /// <param name="message">The message to summarize this exception.</param> /// <param name="existingBinding">The binding that is already bound.</param> /// <param name="redundantBinding">The new binding that conflicts with the already bound binding.</param> internal HotkeyAlreadyBoundException(string message, HotkeyBinding existingBinding, HotkeyBinding redundantBinding) : base(message) { ExistingBinding = existingBinding; RedundantBinding = redundantBinding; }