-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.cpp
More file actions
1251 lines (1159 loc) · 34.1 KB
/
main.cpp
File metadata and controls
1251 lines (1159 loc) · 34.1 KB
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define WIN32_LEAN_AND_MEAN 1
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdint.h>
typedef uint32_t u32;
#include <windows.h>
#include <shellapi.h>
#include <io.h>
#include <fcntl.h>
#include <stdio.h>
//Test mode: Make backquote act as copilot key (for testing on a keyboard which doesn't have a copilot key)
//Also allows testing invalid sequences
#define TEST 0
//Debug mode: adds a console and logging (enabled for debug builds)
#define DEBUG _DEBUG
//Whether to try to handle invalid key sequences
#define HANDLE_INVALID 1
//Whether to include Alt + Ctrl + Del code (Smart App Control doesn't like it)
#define USE_SAS 0
//Whether to make a build which does not interfere with the keyboard and only displays debug log messages
#define DO_NOTHING 0
//Whether to reinstall the keyboard hook every 1 second (to override programs which install their own key hooks, such as Remote Desktop Connection)
#define REINSTALL_HOOK 1
//Whether to use Raw Input to look for keys that got past the keyboard hook (useless)
#define USE_RAW_INPUT 0
//The timeout for the three key sequence - If it takes longer than this, don't treat it as a copilot key press/release
const int KeyChordTimeout = 30;
//The timeout for the three key sequence timer, used for transitions from LWIN -> LSHIFT -> F23
const int KeyChordTimerTimeout = 100;
#if DEBUG
#include <queue>
#include <string>
#include <atomic>
#include <mutex>
std::queue<std::string> debugStringQueue;
std::mutex debugMutex;
HANDLE debugEvent;
std::atomic_bool debugQuit;
DWORD MyGetTickCount()
{
LARGE_INTEGER performanceCount;
QueryPerformanceCounter(&performanceCount);
return (DWORD)(performanceCount.QuadPart / 10000);
}
DWORD WINAPI DebugThreadMain(void* unused)
{
AllocConsole();
AttachConsole(GetCurrentProcessId());
freopen("CON", "w", stdout);
SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), ENABLE_EXTENDED_FLAGS);
while (!debugQuit)
{
WaitForSingleObject(debugEvent, INFINITE);
while (true)
{
std::string str;
{
std::lock_guard<std::mutex> lockGuard(debugMutex);
if (!debugStringQueue.empty())
{
str = debugStringQueue.front();
debugStringQueue.pop();
}
}
if (str.length() > 0)
{
fwrite(str.c_str(), 1, str.length(), stdout);
}
else
{
break;
}
}
}
return 0;
}
#endif //DEBUG
EXTERN_C_START
#if USE_SAS
HMODULE sasModule;
typedef VOID (WINAPI *SendSAS_Func)(BOOL);
SendSAS_Func SendSAS;
#endif //USE_SAS
void ReplaySuppressedKeys();
enum STATE
{
Idle = 0,
LeftWindows,
LeftShift,
F23,
};
STATE pressState;
STATE releaseState;
LPWSTR commandLine;
int argc;
PWSTR* argv;
HWND mainWindow;
HHOOK globalKeyboardHook;
#if REINSTALL_HOOK
UINT_PTR reattachTimer;
#endif
UINT_PTR activeTimer = 0;
DWORD releaseSequenceTimestamp;
#if HANDLE_INVALID
DWORD outOfPressSequenceTimestamp;
DWORD outOfReleaseSequenceTimestamp;
DWORD leftShiftTimestamp;
DWORD leftShiftTimestamp2;
bool leftShiftDown, leftShiftDown2;
bool outOfPressSequence = false;
bool outOfPressSequenceSuppressLeftShift = false;
bool outOfPressSequenceSuppressLeftWindows = false;
bool outOfReleaseSequence = false;
int pendingInjectedLeftShiftRelease = 0;
#endif //HANDLE_INVALID
bool leftWindowsSuppressed;
bool leftShiftSuppressed;
//bool f23Suppressed;
bool rightCtrlDown;
bool leftCtrlDown, leftAltDown, rightAltDown;
int APIENTRY MyWinMain();
LRESULT CALLBACK MyKeyboardProc(int code, WPARAM wParam, LPARAM lParam);
#if DEBUG
const char* GetVKeyName(int key);
void RegisterVKeyCodes();
void DebugPrintf(const char* format, ...);
//In an attempt to make the keyboard more responsive while the console is processing
//we'll try putting the Windows code on its own dedicated thread and
//use the main thread for the console only.
//This only applies to debug builds.
DWORD WINAPI MainThread(void* unused)
{
int exitCode = MyWinMain();
return exitCode;
}
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
RegisterVKeyCodes();
debugEvent = CreateEvent(NULL, false, false, NULL);
HANDLE hThread = CreateThread(NULL, 0, MainThread, 0, NULL, NULL);
int exitCode = DebugThreadMain(0);
ExitProcess(exitCode);
}
void DebugPrintf2(const char* msg)
{
{
std::lock_guard<std::mutex> myLock(debugMutex);
debugStringQueue.emplace(std::string(msg));
}
SetEvent(debugEvent);
}
void DebugPrintf(const char* format, ...)
{
va_list args;
va_start(args, format);
char buffer[256];
vsprintf_s(buffer, format, args);
DebugPrintf2(buffer);
va_end(args);
}
#endif //DEBUG
#if TEST
void InjectCopilotKeyDown()
{
//proper sequence:
PostMessage(mainWindow, WM_USER, VK_LWIN, 2);
PostMessage(mainWindow, WM_USER, VK_LSHIFT, 2);
PostMessage(mainWindow, WM_USER, VK_F23, 2);
//example invalid sequence:
//PostMessage(mainWindow, WM_USER, VK_LSHIFT, 2);
//PostMessage(mainWindow, WM_USER, VK_F23, 2);
//another example invalid sequence:
//PostMessage(mainWindow, WM_USER, VK_LSHIFT, 2);
//PostMessage(mainWindow, WM_USER, VK_LWIN, 2);
//PostMessage(mainWindow, WM_USER, VK_F23, 2);
}
void InjectCopilotKeyUp()
{
//proper sequence:
PostMessage(mainWindow, WM_USER, VK_F23, 3);
PostMessage(mainWindow, WM_USER, VK_LSHIFT, 3);
PostMessage(mainWindow, WM_USER, VK_LWIN, 3);
//No known invalid sequences have been seen so far?
}
#endif //TEST
void InjectKeyDownAsync(DWORD vKey)
{
#if DEBUG
DebugPrintf(" %d InjectKeyDownAsync %s\n", MyGetTickCount(), GetVKeyName(vKey));
#endif
PostMessage(mainWindow, WM_USER, vKey, 0);
}
void InjectKeyUpAsync(DWORD vKey)
{
#if DEBUG
DebugPrintf(" %d InjectKeyUpAsync %s\n", MyGetTickCount(), GetVKeyName(vKey));
#endif
PostMessage(mainWindow, WM_USER, vKey, 1);
}
void SetKeyDown(INPUT* input, DWORD VKEY);
void SetKeyUp(INPUT* input, DWORD VKEY);
LRESULT CALLBACK MyWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
INPUT input;
switch (msg)
{
case WM_USER:
{
bool isRelease = 0 != (lParam & 1);
if (isRelease)
{
SetKeyUp(&input, (DWORD)wParam);
}
else
{
SetKeyDown(&input, (DWORD)wParam);
}
#if TEST
if (0 != (lParam & 2))
{
//Set a special Extra Info on the key input so that we don't ignore that injected keypress
input.ki.dwExtraInfo = 0x12345678;
}
#endif //TEST
SendInput(1, &input, sizeof(input));
return 0;
}
#if USE_RAW_INPUT
case WM_INPUT:
{
//Raw Input isn't really raw, it's been processed by low level keyboard hooks first
HRAWINPUT handle = (HRAWINPUT)lParam;
RAWINPUT data = {};
data.header.dwSize = sizeof(RAWINPUTHEADER);
UINT size = sizeof(data);
GetRawInputData(handle, RID_INPUT, &data, &size, sizeof(RAWINPUTHEADER));
//#if DEBUG
//const char* pressString = "Other message";
//if (data.data.keyboard.Message == WM_KEYUP) pressString = "released";
//if (data.data.keyboard.Message == WM_KEYDOWN) pressString = "pressed";
//DebugPrintf("Raw Input: %s %s\n", GetVKeyName(data.data.keyboard.VKey), pressString);
//#endif //DEBUG
if (data.data.keyboard.Message == WM_KEYUP)
{
//If F23 key is detected as being released here, then somehow it didn't get rejected by the hook
//Force right ctrl to be released in case that happens
if (data.data.keyboard.VKey == VK_F23)
{
InjectKeyUpAsync(VK_RCONTROL);
}
}
}
return 0;
#endif
}
return DefWindowProcW(hwnd, msg, wParam, lParam);
}
#if REINSTALL_HOOK
void CALLBACK TimerHandlerToReattachHook(HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime);
#endif
int APIENTRY MyWinMain()
{
#if HANDLE_INVALID
outOfPressSequenceTimestamp = GetTickCount();
leftShiftTimestamp = GetTickCount();
leftShiftTimestamp2 = GetTickCount();
#endif //HANDLE_INVALID
//commandLine = GetCommandLineW();
//argv = CommandLineToArgvW(commandLine, &argc);
if (!DO_NOTHING)
{
HANDLE mutex = OpenMutexA(SYNCHRONIZE, false, "Mutex for NoCopilotKey");
if (mutex == NULL)
{
mutex = CreateMutexA(NULL, true, "Mutex for NoCopilotKey");
}
else
{
return -1;
}
}
#if USE_SAS
sasModule = LoadLibraryA("sas.dll");
if (sasModule != NULL)
{
SendSAS = (SendSAS_Func)GetProcAddress(sasModule, "SendSAS");
}
#endif //USE_SAS
HMODULE module = GetModuleHandleW(NULL);
WNDCLASSW wndClass = {};
wndClass.lpfnWndProc = MyWndProc;
wndClass.hInstance = module;
wndClass.lpszClassName = L"NoCopilotKey Message Window";
ATOM windowClassAtom = RegisterClassW(&wndClass);
mainWindow = CreateWindowExW(0, wndClass.lpszClassName, L"NoCopilotKey", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL);
#if USE_RAW_INPUT
RAWINPUTDEVICE rawInputDevice = {};
rawInputDevice.usUsagePage = 1;
rawInputDevice.usUsage = 6;
rawInputDevice.dwFlags = RIDEV_INPUTSINK;
rawInputDevice.hwndTarget = mainWindow;
if (!DO_NOTHING)
{
BOOL okay = RegisterRawInputDevices(&rawInputDevice, 1, sizeof(RAWINPUTDEVICE));
}
#endif
globalKeyboardHook = SetWindowsHookExW(WH_KEYBOARD_LL, &MyKeyboardProc, module, 0);
int lastError = GetLastError();
#if REINSTALL_HOOK
reattachTimer = SetTimer(mainWindow, 2, 1000, &TimerHandlerToReattachHook);
#endif //REINSTALL_HOOK
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
//TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
#if REINSTALL_HOOK
void CALLBACK TimerHandlerToReattachHook(HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
reattachTimer = SetTimer(mainWindow, reattachTimer, 1000, &TimerHandlerToReattachHook);
UnhookWindowsHookEx(globalKeyboardHook);
globalKeyboardHook = SetWindowsHookExW(WH_KEYBOARD_LL, &MyKeyboardProc, GetModuleHandle(NULL), 0);
}
#endif //REINSTALL_HOOK
#if HANDLE_INVALID
void SetLeftShiftDown(bool isDown)
{
#if DEBUG
if (isDown != leftShiftDown)
{
DebugPrintf(" Left shift changed: %d -> %d\n", leftShiftDown, isDown);
}
#endif //DEBUG
leftShiftDown2 = leftShiftDown;
leftShiftDown = isDown;
leftShiftTimestamp2 = leftShiftTimestamp2;
leftShiftTimestamp = GetTickCount();
}
#endif //HANDLE_INVALID
void SetPressState(STATE state)
{
#if DEBUG
if (pressState != state)
{
DebugPrintf(" Press State Transition: %d -> %d\n", pressState, state);
}
#endif //DEBUG
pressState = state;
}
void SetReleaseState(STATE state)
{
#if DEBUG
if (releaseState != state)
{
DebugPrintf(" Release State Transition: %d -> %d\n", releaseState, state);
}
#endif //DEBUG
releaseState = state;
}
void CancelTimer();
void CALLBACK TimerProc(HWND hWnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
#if DEBUG
DebugPrintf(" %d TimerProc (took too long to see all three keys)\n", MyGetTickCount());
#endif
ReplaySuppressedKeys();
}
void EnsureTimer()
{
if (activeTimer == 0)
{
activeTimer = SetTimer(mainWindow, 1, KeyChordTimerTimeout, TimerProc);
#if DEBUG
DebugPrintf(" Timer set\n");
#endif
}
}
void CancelTimer()
{
if (activeTimer != 0)
{
KillTimer(mainWindow, activeTimer);
activeTimer = 0;
#if DEBUG
DebugPrintf(" Timer cancelled\n");
#endif
}
}
void SetKeyDown(INPUT* input, DWORD VKEY)
{
input->type = INPUT_KEYBOARD;
input->ki.wVk = (WORD)VKEY;
input->ki.wScan = 0;
input->ki.dwFlags = 0;
input->ki.time = 0;
input->ki.dwExtraInfo = 0;
}
void SetKeyUp(INPUT* input, DWORD VKEY)
{
SetKeyDown(input, VKEY);
input->ki.dwFlags = KEYEVENTF_KEYUP;
}
bool HaveSuppressedKeys()
{
return leftWindowsSuppressed || leftShiftSuppressed;
}
void ReplaySuppressedKeys()
{
if (leftWindowsSuppressed)
{
leftWindowsSuppressed = false;
InjectKeyDownAsync(VK_LWIN);
}
if (leftShiftSuppressed)
{
leftShiftSuppressed = false;
InjectKeyDownAsync(VK_LSHIFT);
}
CancelTimer();
}
LRESULT CALLBACK MyKeyboardProc2(int code, WPARAM wParam, LPARAM lParam)
{
//cooperate with other programs which use low level keyboard hooks
if (code < 0)
{
return CallNextHookEx(NULL, code, wParam, lParam);
}
int keyCode;
int flags;
KBDLLHOOKSTRUCT* hookStruct = (KBDLLHOOKSTRUCT*)lParam;
flags = hookStruct->flags;
keyCode = hookStruct->vkCode;
bool injected = 0 != (flags & LLKHF_INJECTED);
bool released = 0 != (flags & (1 << 7));
bool pressed = !released;
#if TEST
//Special Extra info indicates that we don't ignore a special injected keypress
if (hookStruct->dwExtraInfo == 0x12345678)
{
injected = false;
}
#endif //TEST
if (injected)
{
#if HANDLE_INVALID
if (outOfPressSequence && keyCode == VK_LSHIFT)
{
if (pendingInjectedLeftShiftRelease == 2)
{
#if DEBUG
DebugPrintf(" Special: An out-of-sequence F23 press requested that Left Shift be released.\n"
" But another press to Left Shift happened before the key release was handled.\n"
" Accepting the Left Shift press and rejecting the injected Left Shift release.\n");
#endif
pendingInjectedLeftShiftRelease = 0;
return -1;
}
else if (pendingInjectedLeftShiftRelease == 1)
{
#if DEBUG
DebugPrintf(" Injected Left shift release was accepted.\n");
#endif
pendingInjectedLeftShiftRelease = 0;
}
}
#endif //HANDLE_INVALID
return CallNextHookEx(NULL, code, wParam, lParam);
}
if (DO_NOTHING)
{
return CallNextHookEx(NULL, code, wParam, lParam);
}
#if HANDLE_INVALID
if (outOfPressSequence)
{
DWORD outOfPressSequenceElapsedTime = GetTickCount() - outOfPressSequenceTimestamp;
if (outOfPressSequenceElapsedTime > KeyChordTimeout)
{
outOfPressSequence = false;
}
}
if (outOfReleaseSequence)
{
DWORD outOfReleaseSequenceElapsedTime = GetTickCount() - outOfReleaseSequenceTimestamp;
if (outOfReleaseSequenceElapsedTime > KeyChordTimeout)
{
outOfReleaseSequence = false;
}
}
#endif //HANDLE_INVALID
if (pressed)
{
#if TEST
if (keyCode == VK_OEM_3) // make ` key count as copilot key for test build
{
InjectCopilotKeyDown();
return -1;
}
#endif //TEST
#if HANDLE_INVALID
//any key press ends an out-of-sequence key release sequence
outOfReleaseSequence = false;
#endif //HANDLE_INVALID
if (keyCode == VK_LWIN)
{
ReplaySuppressedKeys();
leftWindowsSuppressed = true;
SetPressState(STATE::LeftWindows);
EnsureTimer();
#if HANDLE_INVALID
if (outOfPressSequence && outOfPressSequenceSuppressLeftWindows)
{
#if DEBUG
DebugPrintf(" Left windows rejected because it was within 30ms of out-of-sequence F23\n");
#endif
SetPressState(STATE::Idle);
outOfPressSequenceSuppressLeftWindows = false;
//don't replay left windows key
leftWindowsSuppressed = false;
}
#endif //HANDLE_INVALID
return -1; //block LWIN key
}
if (pressState == STATE::LeftWindows)
{
if (keyCode == VK_LSHIFT)
{
leftShiftSuppressed = true;
SetPressState(STATE::LeftShift);
#if HANDLE_INVALID
if (outOfPressSequence && outOfPressSequenceSuppressLeftShift)
{
#if DEBUG
DebugPrintf(" Left shift rejected because it was within 30ms of out-of-sequence F23\n");
#endif
outOfPressSequenceSuppressLeftShift = false;
//don't replay left windows key
leftShiftSuppressed = false;
}
#endif
return -1; //block LSHIFT key
}
#if HANDLE_INVALID
else if (keyCode == VK_F23)
{
//Left Windows -> F23 breaks the sequence
#if DEBUG
DebugPrintf(" Out-of-sequence key press: LWIN -> F23\n");
#endif
//keep Left Windows Key suppressed (don't replay it later)
if (leftWindowsSuppressed)
{
leftWindowsSuppressed = false;
}
outOfPressSequenceTimestamp = GetTickCount();
outOfPressSequence = true;
pendingInjectedLeftShiftRelease = 0;
outOfPressSequenceSuppressLeftShift = false;
//Possibility of bad sequence: LShift LWin F23 or LWin F23 LShift
//Was LShift last pressed within 30ms? (LShift LWin F23)
if (leftShiftDown && ((GetTickCount() - leftShiftTimestamp) <= KeyChordTimeout))
{
//Was LShift previously in a pressed state?
if (leftShiftDown2)
{
//Left shift was held down when seeing a left shift press, we don't want Left Shift Released, leave it alone
#if DEBUG
DebugPrintf(" Left shift was held down, do not release the key\n");
#endif
}
else
{
#if DEBUG
DebugPrintf(" Left shift had become pressed within 30ms, release the key\n");
#endif
//send Left Shift Released to cancel the prior keypress
InjectKeyUpAsync(VK_LSHIFT);
pendingInjectedLeftShiftRelease = 1;
//Reset leftShiftDown flag to false to avoid stuck shift key
SetLeftShiftDown(false);
}
}
else
{
//Possibility of LWin F23 LShift (in the future)
//Suppress Left Shift if it is pressed with 30ms
outOfPressSequenceSuppressLeftShift = true;
#if DEBUG
DebugPrintf(" Left shift wasn't pressed, next Left shift within 30ms will be suppressed\n");
#endif
}
SetPressState(STATE::Idle);
SetReleaseState(STATE::F23);
CancelTimer();
leftWindowsSuppressed = false;
InjectKeyDownAsync(VK_RCONTROL);
return -1; //block F23 key
}
#endif //HANDLE_INVALID
else
{
//For keys that aren't in the sequence
SetPressState(STATE::Idle);
if (HaveSuppressedKeys())
{
ReplaySuppressedKeys();
//block key now then enqueue it for replay afterwards
//so that the key happens after the press to LWIN or LSHIFT
InjectKeyDownAsync(keyCode);
return -1; //block F23 key
}
}
}
else if (pressState == STATE::LeftShift)
{
if (keyCode == VK_F23)
{
SetPressState(STATE::Idle);
SetReleaseState(STATE::F23);
CancelTimer();
leftShiftSuppressed = false;
leftWindowsSuppressed = false;
//Copilot Key is a repeating key, but a real right ctrl key doesn't repeat
//Ignore repeated presses
if (!rightCtrlDown)
{
InjectKeyDownAsync(VK_RCONTROL);
}
return -1; //block F23 key
}
else
{
//For keys that aren't in the sequence
SetPressState(STATE::Idle);
if (HaveSuppressedKeys())
{
ReplaySuppressedKeys();
//block key now then enqueue it for replay afterwards
//so that the key happens after the press to LWIN or LSHIFT
InjectKeyDownAsync(keyCode);
return -1;
}
}
}
#if HANDLE_INVALID
if (keyCode == VK_F23)
{
//Out of sequence keypress to F23
#if DEBUG
DebugPrintf(" Out-of-sequence key press: F23\n");
#endif
//possible sequences handled here:
//F23
//F23 LShift
//F23 LShift LWin
//LShift F23
//LShift F23 LWin
//F23 LWin LShift
//sequences handled elsewhere:
//LWin LShift F23 (proper sequence)
//LWin F23 LShift (handled by LWin -> F23 code)
//LWin F23 (handled by LWin -> F23 code)
//LShift LWin F23 (handled by LWin -> F23 code)
//so far, only correct sequence and LShift F23 have been seen, LShift LWin F23 has allegedly been seen too
outOfPressSequenceTimestamp = GetTickCount();
outOfPressSequence = true;
pendingInjectedLeftShiftRelease = 0;
outOfPressSequenceSuppressLeftShift = false;
//To handle the cases where LShift comes before F23:
//left shift may have been pressed with 30ms, if it was, release left shift unless it was held down
if (leftShiftDown && ((GetTickCount() - leftShiftTimestamp) <= KeyChordTimeout))
{
//Was LShift previously in a pressed state?
if (leftShiftDown2)
{
//Left shift was held down when seeing a left shift press, we don't want Left Shift Released, leave it alone
#if DEBUG
DebugPrintf(" Left shift was held down, do not release the key\n");
#endif
}
else
{
#if DEBUG
DebugPrintf(" Left shift had become pressed within 30ms, release the key\n");
#endif
//send Left Shift Released to cancel the prior keypress
InjectKeyUpAsync(VK_LSHIFT);
pendingInjectedLeftShiftRelease = 1;
//Reset leftShiftDown flag to false to avoid stuck shift key
SetLeftShiftDown(false);
}
}
else
{
//Possibility of LShift in the future as part of the sequence
//Suppress Left Shift if it is pressed with 30ms
outOfPressSequenceSuppressLeftShift = true;
#if DEBUG
DebugPrintf(" Left shift wasn't pressed, next Left shift within 30ms will be suppressed\n");
#endif
}
SetPressState(STATE::Idle);
SetReleaseState(STATE::F23);
CancelTimer();
outOfPressSequenceSuppressLeftWindows = true;
leftWindowsSuppressed = false;
InjectKeyDownAsync(VK_RCONTROL);
return -1; //block F23 key
}
if (keyCode == VK_LSHIFT)
{
if (outOfPressSequence && outOfPressSequenceSuppressLeftShift)
{
#if DEBUG
DebugPrintf(" Left shift rejected because it was within 30ms of out-of-sequence F23\n");
#endif
outOfPressSequenceSuppressLeftShift = false;
return -1;
}
if (outOfPressSequence && pendingInjectedLeftShiftRelease == 1)
{
#if DEBUG
DebugPrintf(" Left shift pressed while injected release not yet handled\n");
#endif
pendingInjectedLeftShiftRelease = 2;
}
//Left Shift is tracked by the program in order to detect the invalid sequence LSHIFT F23
SetLeftShiftDown(true);
if (leftShiftDown2)
{
#if DEBUG
DebugPrintf(" Left shift pressed while already held down\n");
#endif
}
}
//Allow other keys to force-break an invalid sequence
if (!(keyCode == VK_F23 || keyCode == VK_LSHIFT || keyCode == VK_LWIN))
{
outOfPressSequence = false;
}
#endif //HANDLE_INVALID
}
else if (released)
{
#if TEST
if (keyCode == VK_OEM_3) // make ` key count as copilot key for a test mode build
{
InjectCopilotKeyUp();
return -1;
}
#endif //TEST
#if HANDLE_INVALID
//Allow releasing any key to force-break an invalid sequence
outOfPressSequence = false;
#endif
if (keyCode == VK_F23 && releaseState == STATE::F23)
{
#if HANDLE_INVALID
SetPressState(STATE::Idle);
CancelTimer();
#endif //HANDLE_INVALID
SetReleaseState(STATE::LeftShift);
InjectKeyUpAsync(VK_RCONTROL);
releaseSequenceTimestamp = GetTickCount();
return -1; //block F23 key release
}
if (keyCode == VK_LSHIFT && releaseState == STATE::LeftShift)
{
SetReleaseState(STATE::LeftWindows);
return -1; //block LSHIFT key release
}
if (keyCode == VK_LWIN && releaseState == STATE::LeftWindows)
{
SetReleaseState(STATE::Idle);
return -1; //block LWIN key release
}
#if HANDLE_INVALID
if (keyCode == VK_LSHIFT)
{
SetLeftShiftDown(false);
}
if (keyCode == VK_F23)
{
//Out-of-sequence F23 key release
#if DEBUG
DebugPrintf(" Out-of-sequence F23 key release\n");
#endif
//This only happens when there is an F23 release without a corresponding handled F23 press
//We don't have a good way to handle this, so just treat all keys as if they are being released.
InjectKeyUpAsync(VK_RCONTROL);
InjectKeyUpAsync(VK_LSHIFT);
InjectKeyUpAsync(VK_LWIN);
InjectKeyUpAsync(VK_F23);
return -1;
}
#endif //HANDLE_INVALID
if (pressState != STATE::Idle)
{
bool leftWindowsWasSuppressed = leftWindowsSuppressed;
bool leftShiftWasSuppressed = leftShiftSuppressed;
ReplaySuppressedKeys();
SetPressState(STATE::Idle);
//Game Bar is weird, you need to inject a key up event and suppress the real key up
//otherwise Game Bar sees the injected Key Down after the real Key Up.
if (leftWindowsWasSuppressed && keyCode == VK_LWIN)
{
InjectKeyUpAsync(VK_LWIN);
return -1;
}
if (leftShiftWasSuppressed && keyCode == VK_LSHIFT)
{
InjectKeyUpAsync(VK_LSHIFT);
return -1;
}
}
}
return CallNextHookEx(NULL, code, wParam, lParam);
}
LRESULT CALLBACK MyKeyboardProc(int code, WPARAM wParam, LPARAM lParam)
{
int keyCode;
int flags;
KBDLLHOOKSTRUCT* hookStruct = (KBDLLHOOKSTRUCT*)lParam;
flags = hookStruct->flags;
keyCode = hookStruct->vkCode;
bool injected = 0 != (flags & LLKHF_INJECTED);
bool released = 0 != (flags & (1 << 7));
bool pressed = !released;
bool handled = false;
#if DEBUG
DWORD arrivalTime = MyGetTickCount();
const char* injectedMessage = " Real KB ";
if (injected)
{
injectedMessage = "INJECTED ";
}
const char* pressedMessage = " PRESS ";
if (released)
{
pressedMessage = "RELEASE ";
}
if (keyCode > 0)
{
DebugPrintf("%d %s%s0x%02X %s\n", arrivalTime, injectedMessage, pressedMessage, keyCode, GetVKeyName(keyCode));
}
#endif //DEBUG
LRESULT result = MyKeyboardProc2(code, wParam, lParam);
#if DEBUG
if (keyCode > 0 && result != 0)
{
DebugPrintf(" %d %s%s0x%02X %s was suppressed\n", arrivalTime, injectedMessage, pressedMessage, keyCode, GetVKeyName(keyCode));
}
#endif //DEBUG
if (result == 0)
{
if (pressed)
{
if (keyCode == VK_LMENU)
{
leftAltDown = true;
}
if (keyCode == VK_RMENU)
{
rightAltDown = true;
}
if (keyCode == VK_LCONTROL)
{
leftCtrlDown = true;
}
if (keyCode == VK_RCONTROL && injected)
{
rightCtrlDown = true;
}
if (keyCode == VK_DELETE)
{
if ((leftAltDown || rightAltDown) && (leftCtrlDown || rightCtrlDown))
{
#if USE_SAS
#if DEBUG
DebugPrintf("Sending Alt + Ctrl + Del (SendSAS)\n");
#endif
if (SendSAS != NULL) SendSAS(true);
#endif //USE_SAS
}
}
}
else
{
if (keyCode == VK_LMENU)
{
leftAltDown = false;
}
if (keyCode == VK_RMENU)
{
rightAltDown = false;
}
if (keyCode == VK_LCONTROL)
{
leftCtrlDown = false;
}
if (keyCode == VK_RCONTROL && injected)
{
rightCtrlDown = false;
}
}
}
return result;
}
#if DEBUG
const char *vkeyList[256];
void RegisterVKeyCode(const char* keyName, int keyCode)