-
-
Notifications
You must be signed in to change notification settings - Fork 46
/
GlobalHotkeys.cs
268 lines (234 loc) · 10.8 KB
/
GlobalHotkeys.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
// <copyright file="GlobalHotkeys.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
//
// Copyright (c) 2023-2023 Peter Kirmeier
namespace SystemTrayMenu.Helpers
{
using System;
using System.Text;
using System.Windows.Input;
using SystemTrayMenu.DllImports;
using SystemTrayMenu.Utilities;
internal static class GlobalHotkeys
{
private static readonly object LastIdLock = new();
private static int lastId = 0;
/// <summary>
/// Registers a global hotkey in a thread safe manner.
/// Throws an InvalidOperationException on error.
/// The caller needs to call UnregisterHotkey to free up ressources.
/// </summary>
/// <param name="hWnd">Window handle receiving the events.</param>
/// <param name="modifiers">Hotkey modifiers.</param>
/// <param name="key">Hotkey major key.</param>
/// <returns>ID of registered key.</returns>
internal static int RegisterHotkeyGlobal(IntPtr hWnd, ModifierKeys modifiers, Key key)
{
lock (LastIdLock)
{
lastId = RegisterHotkeyLocal(hWnd, lastId + 1, modifiers, key);
}
return lastId;
}
/// <summary>
/// Registers a global hotkey in a thread safe manner.
/// Throws an InvalidOperationException on error.
/// The caller needs to call UnregisterHotkey to free up ressources.
/// </summary>
/// <param name="hWnd">Window handle receiving the events.</param>
/// <param name="hotKeyString">Hotkey string description.</param>
/// <returns>ID of registered key.</returns>
internal static int RegisterHotkeyGlobal(IntPtr hWnd, string hotKeyString)
{
ModifierKeys modifiers = ModifierKeysFromString(hotKeyString);
Key key = KeyFromString(hotKeyString);
return RegisterHotkeyGlobal(hWnd, modifiers, key);
}
/// <summary>
/// Registers a local hotkey (with given ID).
/// Throws an InvalidOperationException on error.
/// The caller needs to call UnregisterHotkey to free up ressources.
/// </summary>
/// <param name="hWnd">Window handle receiving the events.</param>
/// <param name="id">ID for the registration.</param>
/// <param name="modifiers">Hotkey modifiers.</param>
/// <param name="key">Hotkey major key.</param>
/// <returns>ID of registered key.</returns>
internal static int RegisterHotkeyLocal(IntPtr hWnd, int id, ModifierKeys modifiers, Key key)
{
int virtualKeyCode = KeyInterop.VirtualKeyFromKey(key);
if (!NativeMethods.User32RegisterHotKey(hWnd, id, (uint)modifiers, (uint)virtualKeyCode))
{
string errorHint = NativeMethods.GetLastErrorHint();
throw new InvalidOperationException(Translator.GetText("Could not register the hot key.") + " (" + errorHint + ")");
}
return id;
}
/// <summary>
/// Registers a local hotkey (with given ID).
/// Throws an InvalidOperationException on error.
/// The caller needs to call UnregisterHotkey to free up ressources.
/// </summary>
/// <param name="hWnd">Window handle receiving the events.</param>
/// <param name="id">ID for the registration.</param>
/// <param name="hotKeyString">Hotkey string description.</param>
/// <returns>ID of registered key.</returns>
internal static int RegisterHotkeyLocal(IntPtr hWnd, int id, string hotKeyString)
{
ModifierKeys modifiers = ModifierKeysFromString(hotKeyString);
Key key = KeyFromString(hotKeyString);
return RegisterHotkeyLocal(hWnd, id, modifiers, key);
}
/// <summary>
/// Unregisters a local or global hotkey.
/// </summary>
/// <param name="hWnd">Window handle.</param>
/// <param name="id">ID for the registration.</param>
internal static void UnregisterHotkey(IntPtr hWnd, int id) => NativeMethods.User32UnregisterHotKey(hWnd, id);
internal static ModifierKeys ModifierKeysFromString(string modifiersString)
{
ModifierKeys modifiers = ModifierKeys.None;
string upper = modifiersString.ToUpperInvariant();
if (upper.Contains("ALT+", StringComparison.InvariantCulture))
{
modifiers |= ModifierKeys.Alt;
}
if (upper.Contains("CTRL+", StringComparison.InvariantCulture) ||
upper.Contains("STRG+", StringComparison.InvariantCulture))
{
modifiers |= ModifierKeys.Control;
}
if (upper.Contains("SHIFT+", StringComparison.InvariantCulture))
{
modifiers |= ModifierKeys.Shift;
}
// LWin and RWin keys will implicitly set Windows key modifier
if (upper.Contains("WIN+", StringComparison.InvariantCulture) ||
upper.EndsWith("LWIN", StringComparison.InvariantCulture) ||
upper.EndsWith("RWIN", StringComparison.InvariantCulture))
{
modifiers |= ModifierKeys.Windows;
}
return modifiers;
}
internal static Key KeyFromString(string keyString)
{
Key key = Key.None;
if (!string.IsNullOrEmpty(keyString))
{
if (keyString.LastIndexOf('+') > 0)
{
keyString = keyString.Remove(0, keyString.LastIndexOf('+') + 1).Trim();
}
keyString = keyString.
Replace("PgDn", "PageDown", StringComparison.InvariantCulture).
Replace("PgUp", "PageUp", StringComparison.InvariantCulture);
if (!Enum.TryParse(keyString, true, out key))
{
Log.Warn($"{keyString} cannot be parsed", new());
}
}
return key;
}
internal static string HotkeyToLocalizedString(ModifierKeys modifiers, Key key)
{
StringBuilder hotkeyString = new();
if ((modifiers & ModifierKeys.Alt) != 0)
{
hotkeyString.Append(GetKeyName(Key.LeftAlt)).Append(" + ");
}
if ((modifiers & ModifierKeys.Control) != 0)
{
hotkeyString.Append(GetKeyName(Key.LeftCtrl)).Append(" + ");
}
if ((modifiers & ModifierKeys.Shift) != 0)
{
hotkeyString.Append(GetKeyName(Key.LeftShift)).Append(" + ");
}
if ((modifiers & ModifierKeys.Windows) != 0)
{
hotkeyString.Append("Win").Append(" + ");
}
return hotkeyString.ToString() + GetKeyName(key);
}
private static string GetKeyName(Key key)
{
const uint MAPVK_VK_TO_VSC = 0;
const uint KF_EXTENDED = 0x100;
const uint SCANCODE_SIMULATED = 0x200;
const uint scanCodeNumPad = 0x37;
const uint scanCodePause = 0x45;
StringBuilder keyName = new(100);
string keyString = string.Empty;
switch (key)
{
case Key.Multiply:
if (NativeMethods.User32GetKeyNameText(scanCodeNumPad << 16, keyName, keyName.Capacity) > 0)
{
keyString = keyName.ToString().Replace("*", string.Empty, StringComparison.InvariantCulture).Trim().ToLowerInvariant();
if (keyString.Contains('('))
{
return "* " + keyString;
}
keyString = keyString[..1].ToUpperInvariant() + keyString[1..].ToLowerInvariant();
}
return keyString + " *";
case Key.Divide:
if (NativeMethods.User32GetKeyNameText(scanCodeNumPad << 16, keyName, keyName.Capacity) > 0)
{
keyString = keyName.ToString().Replace("*", string.Empty, StringComparison.InvariantCulture).Trim().ToLowerInvariant();
if (keyString.Contains('('))
{
return "/ " + keyString;
}
keyString = keyString[..1].ToUpperInvariant() + keyString[1..].ToLowerInvariant();
}
return keyString + " /";
}
// Converting Windows Input Key Enums into Virtual-Key Codes into Scan Codes into Text
// - Windows Input Key Enums: https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.key?view=windowsdesktop-7.0
// - Virtual-Key Codes: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes
// - Scan Codes: https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input#scan-codes
uint virtualKeyCode = (uint)KeyInterop.VirtualKeyFromKey(key);
uint scanCode = NativeMethods.User32MapVirtualKey(virtualKeyCode, MAPVK_VK_TO_VSC);
// Handle names of some special keys
switch (key)
{
case Key.Left:
case Key.Up:
case Key.Right:
case Key.Down: // arrow keys
case Key.Prior:
case Key.Next: // page up and page down
case Key.End:
case Key.Home:
case Key.Insert:
case Key.Delete:
case Key.NumLock:
scanCode |= KF_EXTENDED; // set extended bit (simulate origin from enhanced 101/102-key keyboard)
break;
case Key.PrintScreen:
scanCode = KF_EXTENDED | scanCodeNumPad;
break;
case Key.Pause:
scanCode = scanCodePause;
break;
}
scanCode |= SCANCODE_SIMULATED;
if (NativeMethods.User32GetKeyNameText(scanCode << 16, keyName, keyName.Capacity) != 0)
{
string visibleName = keyName.ToString();
if (visibleName.Length > 1)
{
visibleName = visibleName[..1] + visibleName[1..].ToLowerInvariant();
}
return visibleName;
}
else
{
return key.ToString();
}
}
}
}