Skip to content

Commit

Permalink
Fix issue that key modifiers are parsed wrong
Browse files Browse the repository at this point in the history
(registering the hotkey might have failed)
Simplified hot key pressed events
Remove obsolete class KeyPressedEventArgs
  • Loading branch information
topeterk committed May 22, 2023
1 parent f8c9913 commit f55af05
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 132 deletions.
10 changes: 5 additions & 5 deletions Business/KeyboardInput.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,18 @@ public void Dispose()
hook.Dispose();
}

internal bool RegisterHotKey(string hotKey)
internal bool RegisterHotKey(string hotKeyString)
{
if (!string.IsNullOrEmpty(hotKey))
if (!string.IsNullOrEmpty(hotKeyString))
{
try
{
hook.RegisterHotKey();
hook.KeyPressed += (sender, e) => HotKeyPressed?.Invoke();
hook.RegisterHotKey(hotKeyString);
hook.KeyPressed += (_, _) => HotKeyPressed?.Invoke();
}
catch (InvalidOperationException ex)
{
Log.Warn($"Hotkey cannot be set: '{hotKey}'", ex);
Log.Warn($"Hotkey cannot be set: '{hotKeyString}'", ex);
return false;
}
}
Expand Down
27 changes: 0 additions & 27 deletions Helpers/KeyPressedEventArgs.cs

This file was deleted.

79 changes: 12 additions & 67 deletions Helpers/KeyboardHook.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,6 @@ namespace SystemTrayMenu.Helpers
using SystemTrayMenu.Utilities;
using static SystemTrayMenu.Utilities.FormsExtensions;

/// <summary>
/// The enumeration of possible modifiers.
/// </summary>
[Flags]
public enum KeyboardHookModifierKeys : uint
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Win = 8,
}

public sealed class KeyboardHook : IDisposable
{
private readonly Window window = new();
Expand All @@ -32,83 +19,41 @@ public sealed class KeyboardHook : IDisposable
public KeyboardHook()
{
// register the event of the inner native window.
window.KeyPressed += Window_KeyPressed;
window.KeyPressed += (key, modifiers) => KeyPressed?.Invoke(key, modifiers);
}

/// <summary>
/// A hot key has been pressed.
/// </summary>
internal event EventHandler<KeyPressedEventArgs>? KeyPressed;
internal event Action<Key, ModifierKeys>? KeyPressed;

public void Dispose()
{
// unregister all the registered hot keys.
for (int i = currentId; i > 0; i--)
{
DllImports.NativeMethods.User32UnregisterHotKey(window.Handle, i);
NativeMethods.User32UnregisterHotKey(window.Handle, i);
}

// dispose the inner native window.
window.KeyPressed -= Window_KeyPressed;
window.Dispose();
}

internal void RegisterHotKey()
internal void RegisterHotKey(string hotKeyString)
{
KeyboardHookModifierKeys modifiers = KeyboardHookModifierKeys.None;
string modifiersString = Properties.Settings.Default.HotKey;
if (!string.IsNullOrEmpty(modifiersString))
{
if (modifiersString.ToUpperInvariant().Contains("ALT", StringComparison.InvariantCulture))
{
modifiers |= KeyboardHookModifierKeys.Alt;
}
// TODO: Replace old code of v1 with HotKeyControl methods like here
// as there is a bug in the body of this function (missing "+" when checking for modifiers)
ModifierKeys modifiers = HotkeyControl.HotkeyModifiersFromString(hotKeyString);
Key hotkey = HotkeyControl.HotkeyFromString(hotKeyString);

if (modifiersString.ToUpperInvariant().Contains("CTRL", StringComparison.InvariantCulture) ||
modifiersString.ToUpperInvariant().Contains("STRG", StringComparison.InvariantCulture))
{
modifiers |= KeyboardHookModifierKeys.Control;
}

if (modifiersString.ToUpperInvariant().Contains("SHIFT", StringComparison.InvariantCulture))
{
modifiers |= KeyboardHookModifierKeys.Shift;
}

if (modifiersString.ToUpperInvariant().Contains("WIN", StringComparison.InvariantCulture))
{
modifiers |= KeyboardHookModifierKeys.Win;
}
}

RegisterHotKey(modifiers, HotkeyControl.HotkeyFromString(Properties.Settings.Default.HotKey));
}

/// <summary>
/// Registers a hot key in the system.
/// </summary>
/// <param name="key">The key itself that is associated with the hot key.</param>
internal void RegisterHotKey(Key key)
{
uint keyModifiersNone = 0;
RegisterHotKey(keyModifiersNone, key);
RegisterHotKey((uint)modifiers, hotkey);
}

/// <summary>
/// Registers a hot key in the system.
/// </summary>
/// <param name="modifier">The modifiers that are associated with the hot key.</param>
/// <param name="key">The key itself that is associated with the hot key.</param>
internal void RegisterHotKey(KeyboardHookModifierKeys modifier, Key key)
{
RegisterHotKey((uint)modifier, key);
}

private void Window_KeyPressed(object? sender, KeyPressedEventArgs e)
{
KeyPressed?.Invoke(this, e);
}

private void RegisterHotKey(uint modifier, Key key)
{
currentId += 1;
Expand All @@ -127,7 +72,7 @@ private class Window : NativeWindow, IDisposable
{
private const int WmHotkey = 0x0312;

public event EventHandler<KeyPressedEventArgs>? KeyPressed;
public event Action<Key, ModifierKeys>? KeyPressed;

/// <summary>
/// Overridden to get the notifications.
Expand All @@ -139,10 +84,10 @@ protected override IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lP
{
// get the keys.
Key key = (Key)(((int)lParam >> 16) & 0xFFFF);
KeyboardHookModifierKeys modifier = (KeyboardHookModifierKeys)((int)lParam & 0xFFFF);
ModifierKeys modifiers = (ModifierKeys)((int)lParam & 0xFFFF);

// invoke the event to notify the parent.
KeyPressed?.Invoke(this, new KeyPressedEventArgs(modifier, key));
KeyPressed?.Invoke(key, modifiers);
}

handled = false;
Expand Down
60 changes: 30 additions & 30 deletions NativeDllImport/HotKey.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
// <copyright file="HotKey.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

namespace SystemTrayMenu.DllImports
{
using System;
// <copyright file="HotKey.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>

namespace SystemTrayMenu.DllImports
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;

/// <summary>
/// wraps the methodcalls to native windows dll's.
/// </summary>
public static partial class NativeMethods
using System.Text;

/// <summary>
/// wraps the methodcalls to native windows dll's.
/// </summary>
public static partial class NativeMethods
{
internal static string GetLastErrorHint()
{
Expand All @@ -26,26 +26,26 @@ internal static string GetLastErrorHint()
};
}

[SupportedOSPlatform("windows")]
[DllImport("user32.dll", EntryPoint = "RegisterHotKey", SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)]
[DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)]
[return: MarshalAs(UnmanagedType.Bool)]
[SupportedOSPlatform("windows")]
[DllImport("user32.dll", EntryPoint = "RegisterHotKey", SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)]
[DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool User32RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint virtualKeyCode);

[SupportedOSPlatform("windows")]
[DllImport("user32.dll", EntryPoint = "UnregisterHotKey", SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
[DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)]
[SupportedOSPlatform("windows")]
[DllImport("user32.dll", EntryPoint = "UnregisterHotKey", SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
[DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)]
internal static extern bool User32UnregisterHotKey(IntPtr hWnd, int id);

[SupportedOSPlatform("windows")]
[DllImport("user32.dll", EntryPoint = "MapVirtualKey", SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)]
[DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)]
[SupportedOSPlatform("windows")]
[DllImport("user32.dll", EntryPoint = "MapVirtualKey", SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)]
[DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)]
internal static extern uint User32MapVirtualKey(uint uCode, uint uMapType);

[SupportedOSPlatform("windows")]
[DllImport("user32.dll", EntryPoint = "GetKeyNameText", SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)]
[DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)]
internal static extern int User32GetKeyNameText(uint lParam, [Out] StringBuilder lpString, int nSize);
}
}
[SupportedOSPlatform("windows")]
[DllImport("user32.dll", EntryPoint = "GetKeyNameText", SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi)]
[DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)]
internal static extern int User32GetKeyNameText(uint lParam, [Out] StringBuilder lpString, int nSize);
}
}
7 changes: 4 additions & 3 deletions Utilities/SingleAppInstance.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ internal static bool Initialize()
{
if (Properties.Settings.Default.SendHotkeyInsteadKillOtherInstances)
{
ModifierKeys modifiers = HotkeyControl.HotkeyModifiersFromString(Properties.Settings.Default.HotKey);
Key hotkey = HotkeyControl.HotkeyFromString(Properties.Settings.Default.HotKey);
string hotKeyString = Properties.Settings.Default.HotKey;
ModifierKeys modifiers = HotkeyControl.HotkeyModifiersFromString(hotKeyString);
Key hotkey = HotkeyControl.HotkeyFromString(hotKeyString);

try
{
Expand Down Expand Up @@ -62,7 +63,7 @@ internal static bool Initialize()
}
catch (Exception ex)
{
Log.Warn($"Send hoktey {Properties.Settings.Default.HotKey} to other instance failed", ex);
Log.Warn($"Send hoktey {hotKeyString} to other instance failed", ex);
}
}
else
Expand Down

0 comments on commit f55af05

Please sign in to comment.