-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
centralized_kb_hook.cpp
276 lines (250 loc) · 9.36 KB
/
centralized_kb_hook.cpp
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
269
270
271
272
273
274
275
276
#include "pch.h"
#include "centralized_kb_hook.h"
#include <common/debug_control.h>
#include <common/utils/winapi_error.h>
#include <common/logger/logger.h>
#include <common/interop/shared_constants.h>
namespace CentralizedKeyboardHook
{
struct HotkeyDescriptor
{
Hotkey hotkey;
std::wstring moduleName;
std::function<bool()> action;
bool operator<(const HotkeyDescriptor& other) const
{
return hotkey < other.hotkey;
};
};
std::multiset<HotkeyDescriptor> hotkeyDescriptors;
std::mutex mutex;
HHOOK hHook{};
// To store information about handling pressed keys.
struct PressedKeyDescriptor
{
DWORD virtualKey; // Virtual Key code of the key we're keeping track of.
std::wstring moduleName;
std::function<bool()> action;
UINT_PTR idTimer; // Timer ID for calling SET_TIMER with.
UINT millisecondsToPress; // How much time the key must be pressed.
bool operator<(const PressedKeyDescriptor& other) const
{
// We'll use the virtual key as the real key, since looking for a hit with the key is done in the more time sensitive path (low level keyboard hook).
return virtualKey < other.virtualKey;
};
};
std::multiset<PressedKeyDescriptor> pressedKeyDescriptors;
std::mutex pressedKeyMutex;
// keep track of last pressed key, to detect repeated keys and if there are more keys pressed.
const DWORD VK_DISABLED = CommonSharedConstants::VK_DISABLED;
DWORD vkCodePressed = VK_DISABLED;
// Save the runner window handle for registering timers.
HWND runnerWindow;
struct DestroyOnExit
{
~DestroyOnExit()
{
Stop();
}
} destroyOnExitObj;
// Handle the pressed key proc
void PressedKeyTimerProc(
HWND hwnd,
UINT /*message*/,
UINT_PTR idTimer,
DWORD /*dwTime*/)
{
std::multiset<PressedKeyDescriptor> copy;
{
// Make a copy, to look for the action to call.
std::unique_lock lock{ pressedKeyMutex };
copy = pressedKeyDescriptors;
}
for (const auto& it : copy)
{
if (it.idTimer == idTimer)
{
it.action();
}
}
KillTimer(hwnd, idTimer);
}
LRESULT CALLBACK KeyboardHookProc(_In_ int nCode, _In_ WPARAM wParam, _In_ LPARAM lParam)
{
if (nCode < 0)
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
const auto& keyPressInfo = *reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam);
if (keyPressInfo.dwExtraInfo == PowertoyModuleIface::CENTRALIZED_KEYBOARD_HOOK_DONT_TRIGGER_FLAG)
{
// The new keystroke was generated from one of our actions. We should pass it along.
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
// Check if the keys are pressed.
if (!pressedKeyDescriptors.empty())
{
bool wasKeyPressed = vkCodePressed != VK_DISABLED;
// Hold the lock for the shortest possible duration
if ((wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))
{
if (!wasKeyPressed)
{
// If no key was pressed before, let's start a timer to take into account this new key.
std::unique_lock lock{ pressedKeyMutex };
PressedKeyDescriptor dummy{ .virtualKey = keyPressInfo.vkCode };
auto [it, last] = pressedKeyDescriptors.equal_range(dummy);
for (; it != last; ++it)
{
SetTimer(runnerWindow, it->idTimer, it->millisecondsToPress, PressedKeyTimerProc);
}
}
else if (vkCodePressed != keyPressInfo.vkCode)
{
// If a different key was pressed, let's clear the timers we have started for the previous key.
std::unique_lock lock{ pressedKeyMutex };
PressedKeyDescriptor dummy{ .virtualKey = vkCodePressed };
auto [it, last] = pressedKeyDescriptors.equal_range(dummy);
for (; it != last; ++it)
{
KillTimer(runnerWindow, it->idTimer);
}
}
vkCodePressed = keyPressInfo.vkCode;
}
if (wParam == WM_KEYUP || wParam == WM_SYSKEYUP)
{
std::unique_lock lock{ pressedKeyMutex };
PressedKeyDescriptor dummy{ .virtualKey = keyPressInfo.vkCode };
auto [it, last] = pressedKeyDescriptors.equal_range(dummy);
for (; it != last; ++it)
{
KillTimer(runnerWindow, it->idTimer);
}
vkCodePressed = 0x100;
}
}
if ((wParam != WM_KEYDOWN) && (wParam != WM_SYSKEYDOWN))
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
Hotkey hotkey{
.win = (GetAsyncKeyState(VK_LWIN) & 0x8000) || (GetAsyncKeyState(VK_RWIN) & 0x8000),
.ctrl = static_cast<bool>(GetAsyncKeyState(VK_CONTROL) & 0x8000),
.shift = static_cast<bool>(GetAsyncKeyState(VK_SHIFT) & 0x8000),
.alt = static_cast<bool>(GetAsyncKeyState(VK_MENU) & 0x8000),
.key = static_cast<unsigned char>(keyPressInfo.vkCode)
};
if (hotkey == Hotkey{})
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
std::function<bool()> action;
{
// Hold the lock for the shortest possible duration
std::unique_lock lock{ mutex };
HotkeyDescriptor dummy{ .hotkey = hotkey };
auto it = hotkeyDescriptors.find(dummy);
if (it != hotkeyDescriptors.end())
{
action = it->action;
}
}
if (action)
{
if (action())
{
// After invoking the hotkey send a dummy key to prevent Start Menu from activating
INPUT dummyEvent[1] = {};
dummyEvent[0].type = INPUT_KEYBOARD;
dummyEvent[0].ki.wVk = 0xFF;
dummyEvent[0].ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(1, dummyEvent, sizeof(INPUT));
// Swallow the key press
return 1;
}
}
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
void SetHotkeyAction(const std::wstring& moduleName, const Hotkey& hotkey, std::function<bool()>&& action) noexcept
{
Logger::trace(L"Register hotkey action for {}", moduleName);
std::unique_lock lock{ mutex };
hotkeyDescriptors.insert({ .hotkey = hotkey, .moduleName = moduleName, .action = std::move(action) });
}
void AddPressedKeyAction(const std::wstring& moduleName, const DWORD vk, const UINT milliseconds, std::function<bool()>&& action) noexcept
{
// Calculate a unique TimerID.
auto hash = std::hash<std::wstring>{}(moduleName); // Hash the module as the upper part of the timer ID.
const UINT upperId = hash & 0xFFFF;
const UINT lowerId = vk & 0xFFFF; // The key to press can be the lower ID.
const UINT timerId = upperId << 16 | lowerId;
std::unique_lock lock{ pressedKeyMutex };
pressedKeyDescriptors.insert({ .virtualKey = vk, .moduleName = moduleName, .action = std::move(action), .idTimer = timerId, .millisecondsToPress = milliseconds });
}
void ClearModuleHotkeys(const std::wstring& moduleName) noexcept
{
Logger::trace(L"UnRegister hotkey action for {}", moduleName);
{
std::unique_lock lock{ mutex };
auto it = hotkeyDescriptors.begin();
while (it != hotkeyDescriptors.end())
{
if (it->moduleName == moduleName)
{
it = hotkeyDescriptors.erase(it);
}
else
{
++it;
}
}
}
{
std::unique_lock lock{ pressedKeyMutex };
auto it = pressedKeyDescriptors.begin();
while (it != pressedKeyDescriptors.end())
{
if (it->moduleName == moduleName)
{
it = pressedKeyDescriptors.erase(it);
}
else
{
++it;
}
}
}
}
void Start() noexcept
{
#if defined(DISABLE_LOWLEVEL_HOOKS_WHEN_DEBUGGED)
const bool hook_disabled = IsDebuggerPresent();
#else
const bool hook_disabled = false;
#endif
if (!hook_disabled)
{
if (!hHook)
{
hHook = SetWindowsHookExW(WH_KEYBOARD_LL, KeyboardHookProc, NULL, NULL);
if (!hHook)
{
DWORD errorCode = GetLastError();
show_last_error_message(L"SetWindowsHookEx", errorCode, L"centralized_kb_hook");
}
}
}
}
void Stop() noexcept
{
if (hHook && UnhookWindowsHookEx(hHook))
{
hHook = NULL;
}
}
void RegisterWindow(HWND hwnd) noexcept
{
runnerWindow = hwnd;
}
}