-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmadpaster.cpp
More file actions
2441 lines (2051 loc) · 83.4 KB
/
madpaster.cpp
File metadata and controls
2441 lines (2051 loc) · 83.4 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
/*
* MadPaster - Windows Keyboard Paste Utility
* Author: Dave Cox
* Version: 3.0.1
* Date: January 31, 2026
*/
#define UNICODE
#define _UNICODE
#include <windows.h>
#include <commctrl.h> // For up-down (spin) control
#include <commdlg.h> // For GetOpenFileName file dialog
#include <shellapi.h> // For Shell_NotifyIcon (system tray)
#include <gdiplus.h> // For PNG image loading
#include <mmsystem.h> // For timeBeginPeriod/timeEndPeriod
#include <string>
#include <vector>
using namespace Gdiplus;
// Link common controls
#pragma comment(lib, "comctl32.lib")
#pragma comment(lib, "gdiplus.lib")
#pragma comment(lib, "winmm.lib")
// ============================================================================
// Constants and Control IDs
// ============================================================================
const int maxchar = 45000;
// Injection modes for different target types
enum class InjectionMode {
Unicode, // KEYEVENTF_UNICODE - works for local apps
VKScancode, // VK codes with scancodes - better for remote clients
Hybrid, // Try VK first, fall back to Unicode
Auto // Detect target type and choose mode
};
// Pacing strategies for input injection
enum class PacingStrategy {
Burst, // Send chunk, pause after - for local targets
PerCharacter, // Pause after each complete character - for remote
PerEvent // Pause between every INPUT event - most conservative
};
// Input injection constants (legacy burst mode)
const int CHUNK_SIZE = 2; // Characters per SendInput batch (conservative)
const int INTER_CHUNK_PAUSE_MS = 25; // Base pause between chunks
const int NEWLINE_PAUSE_MS = 100; // Pause before/after newlines
const int MAX_RETRY_COUNT = 3; // Retries on partial SendInput
const int IDLE_WAIT_MS = 50; // Max wait for WaitForInputIdle
// Per-event pacing constants (new mode)
const int PER_EVENT_DELAY_MS = 2; // Delay between each INPUT event
const int PER_CHAR_DELAY_MS = 5; // Delay after each complete character
const int LINE_START_GUARD_CHARS = 3; // Extra delay for first N chars after newline
const int LINE_START_GUARD_MS = 10; // Extra delay per guard char
// Remote client window classes (null-terminated array)
const wchar_t* REMOTE_WINDOW_CLASSES[] = {
L"TscShellContainerClass", // mstsc.exe (RDP)
L"ICAClientClass", // Citrix Receiver
L"RAIL_WINDOW", // Citrix seamless apps
L"Transparent Windows Client", // Azure Virtual Desktop
L"vncviewer", // VNC clients
L"TightVNC",
L"RealVNC",
L"MozillaWindowClass", // Firefox (noVNC)
L"Chrome_WidgetWin_1", // Chrome/Edge (noVNC, Azure Bastion)
nullptr
};
// Window dimensions
const int WINDOW_WIDTH = 400;
const int WINDOW_HEIGHT = 439;
// Control IDs
#define IDC_RADIO_CLIPBOARD 101
#define IDC_RADIO_FILE 102
#define IDC_EDIT_DELAY 103
#define IDC_SPIN_DELAY 104
#define IDC_BUTTON_ARM 105
#define IDC_BUTTON_BROWSE 106
#define IDC_STATIC_FILEPATH 107
#define IDC_STATIC_STATUS 108
#define IDC_EDIT_KEYSTROKE 109
#define IDC_SPIN_KEYSTROKE 110
#define IDC_COMBO_MODE 111
#define IDC_CHECK_DIAG 112
#define IDC_PROGRESS 113
#define IDC_CHECK_SILENT 114
// Timer IDs
#define IDT_COUNTDOWN 201
// Icons
#define IDI_APPICON 100 // Embedded resource icon
// Tray icon
#define IDI_TRAY 301
#define WM_TRAYICON (WM_USER + 1)
// Tray menu items
#define IDM_TRAY_ARM 401
#define IDM_TRAY_SHOW 402
#define IDM_TRAY_EXIT 403
// Hotkey IDs
#define IDH_PASTE_HOTKEY 501
// Floating progress window
#define FLOATING_PROGRESS_CLASS L"MadPasterFloatingProgress"
#define FLOATING_PROGRESS_WIDTH 300
#define FLOATING_PROGRESS_HEIGHT 70
// ============================================================================
// Global Application State
// ============================================================================
struct AppState {
HINSTANCE hInstance;
HWND hwndMain;
HWND hwndRadioClipboard;
HWND hwndRadioFile;
HWND hwndEditDelay;
HWND hwndSpinDelay;
HWND hwndEditKeystroke;
HWND hwndSpinKeystroke;
HWND hwndComboMode;
HWND hwndCheckDiag;
HWND hwndCheckSilent;
HWND hwndButtonArm;
HWND hwndButtonBrowse;
HWND hwndStaticFilePath;
HWND hwndStaticStatus;
HWND hwndProgress;
HWND hwndLogo;
// Floating progress window (visible when minimized to tray)
HWND hwndFloatingProgress;
HWND hwndFloatingProgressBar;
HWND hwndFloatingLabel;
NOTIFYICONDATA nid;
bool minimizedToTray;
// Custom fonts
HFONT hFontUI;
HFONT hFontMono;
HFONT hFontButton;
// Custom icon
HICON hAppIcon;
// Logo image
Gdiplus::Image* pLogoImage;
ULONG_PTR gdiplusToken;
// Settings
bool useClipboard;
int delaySeconds;
int keystrokeDelayMs;
std::wstring selectedFilePath;
// Countdown state
bool isArmed;
int countdownRemaining;
// Injection settings
InjectionMode injectionMode;
bool diagnosticMode;
bool silentMode;
};
static AppState g_app = {};
// ============================================================================
// File Encoding Support
// ============================================================================
enum class FileEncoding {
UTF8_BOM,
UTF16_LE_BOM,
UTF16_BE_BOM,
ANSI_OR_UTF8
};
// Detect file encoding from BOM
FileEncoding detectEncoding(const std::vector<unsigned char>& buffer) {
if (buffer.size() >= 3 &&
buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) {
return FileEncoding::UTF8_BOM;
}
if (buffer.size() >= 2 && buffer[0] == 0xFF && buffer[1] == 0xFE) {
return FileEncoding::UTF16_LE_BOM;
}
if (buffer.size() >= 2 && buffer[0] == 0xFE && buffer[1] == 0xFF) {
return FileEncoding::UTF16_BE_BOM;
}
return FileEncoding::ANSI_OR_UTF8;
}
// Convert UTF-8 to wide string
std::wstring utf8ToWide(const char* utf8Str, size_t len) {
if (len == 0) return L"";
int wideLen = MultiByteToWideChar(CP_UTF8, 0, utf8Str,
static_cast<int>(len), nullptr, 0);
if (wideLen == 0) return L"";
std::wstring wideStr(wideLen, 0);
MultiByteToWideChar(CP_UTF8, 0, utf8Str, static_cast<int>(len),
&wideStr[0], wideLen);
return wideStr;
}
// Convert ANSI to wide string
std::wstring ansiToWide(const char* ansiStr, size_t len) {
if (len == 0) return L"";
int wideLen = MultiByteToWideChar(CP_ACP, 0, ansiStr,
static_cast<int>(len), nullptr, 0);
if (wideLen == 0) return L"";
std::wstring wideStr(wideLen, 0);
MultiByteToWideChar(CP_ACP, 0, ansiStr, static_cast<int>(len),
&wideStr[0], wideLen);
return wideStr;
}
// ============================================================================
// Clipboard Functions
// ============================================================================
bool openClipboard() {
if (OpenClipboard(nullptr)) {
return true;
} else {
MessageBox(
nullptr,
L"Failed to OpenClipboard.",
L"MadPaster - Error",
MB_OK | MB_ICONERROR | MB_TOPMOST
);
return false;
}
}
void closeClipboard() {
CloseClipboard();
}
std::wstring getClipboardText() {
if (!IsClipboardFormatAvailable(CF_UNICODETEXT)) {
MessageBox(
nullptr,
L"Clipboard does not contain text.",
L"MadPaster - Error",
MB_OK | MB_ICONERROR | MB_TOPMOST
);
return L"";
}
HANDLE hData = GetClipboardData(CF_UNICODETEXT);
if (hData == nullptr) {
MessageBox(
nullptr,
L"Failed to get clipboard data.",
L"MadPaster - Error",
MB_OK | MB_ICONERROR | MB_TOPMOST
);
return L"";
}
wchar_t* pszText = static_cast<wchar_t*>(GlobalLock(hData));
if (pszText == nullptr) {
MessageBox(
nullptr,
L"Failed to lock clipboard data.",
L"MadPaster - Error",
MB_OK | MB_ICONERROR | MB_TOPMOST
);
return L"";
}
std::wstring text(pszText);
GlobalUnlock(hData);
return text;
}
// ============================================================================
// File Reading Functions
// ============================================================================
std::wstring readFileContents(const std::wstring& filePath, bool& success) {
success = false;
HANDLE hFile = CreateFileW(
filePath.c_str(),
GENERIC_READ,
FILE_SHARE_READ,
nullptr,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
nullptr
);
if (hFile == INVALID_HANDLE_VALUE) {
DWORD error = GetLastError();
std::wstring errorMsg = L"Failed to open file.\nError code: " +
std::to_wstring(error) + L"\n\nFile: " + filePath;
MessageBox(nullptr, errorMsg.c_str(), L"MadPaster - File Error",
MB_OK | MB_ICONERROR | MB_TOPMOST);
return L"";
}
LARGE_INTEGER fileSize;
if (!GetFileSizeEx(hFile, &fileSize)) {
CloseHandle(hFile);
MessageBox(nullptr, L"Failed to get file size.", L"MadPaster - File Error",
MB_OK | MB_ICONERROR | MB_TOPMOST);
return L"";
}
const LONGLONG maxFileSize = 500 * 1024; // 500 KB
if (fileSize.QuadPart > maxFileSize) {
CloseHandle(hFile);
MessageBox(nullptr, L"File too large.\nMaximum file size: 500KB",
L"MadPaster - File Error", MB_OK | MB_ICONERROR | MB_TOPMOST);
return L"";
}
if (fileSize.QuadPart == 0) {
CloseHandle(hFile);
MessageBox(nullptr, L"File is empty.",
L"MadPaster - File Error", MB_OK | MB_ICONERROR | MB_TOPMOST);
return L"";
}
std::vector<unsigned char> buffer(static_cast<size_t>(fileSize.QuadPart));
DWORD bytesRead;
if (!ReadFile(hFile, buffer.data(), static_cast<DWORD>(fileSize.QuadPart),
&bytesRead, nullptr)) {
CloseHandle(hFile);
MessageBox(nullptr, L"Failed to read file.", L"MadPaster - File Error",
MB_OK | MB_ICONERROR | MB_TOPMOST);
return L"";
}
CloseHandle(hFile);
FileEncoding encoding = detectEncoding(buffer);
std::wstring result;
switch (encoding) {
case FileEncoding::UTF8_BOM:
result = utf8ToWide(reinterpret_cast<char*>(buffer.data() + 3),
bytesRead - 3);
break;
case FileEncoding::UTF16_LE_BOM:
result = std::wstring(
reinterpret_cast<wchar_t*>(buffer.data() + 2),
(bytesRead - 2) / sizeof(wchar_t)
);
break;
case FileEncoding::UTF16_BE_BOM:
{
size_t charCount = (bytesRead - 2) / sizeof(wchar_t);
result.resize(charCount);
for (size_t i = 0; i < charCount; ++i) {
unsigned char hi = buffer[2 + i * 2];
unsigned char lo = buffer[2 + i * 2 + 1];
result[i] = static_cast<wchar_t>((hi << 8) | lo);
}
}
break;
case FileEncoding::ANSI_OR_UTF8:
default:
result = utf8ToWide(reinterpret_cast<char*>(buffer.data()),
bytesRead);
if (result.empty() && bytesRead > 0) {
result = ansiToWide(reinterpret_cast<char*>(buffer.data()),
bytesRead);
}
break;
}
success = true;
return result;
}
// Show file open dialog and return selected path
std::wstring showFileOpenDialog(HWND hwndOwner) {
wchar_t filePath[MAX_PATH] = {0};
OPENFILENAMEW ofn = {0};
ofn.lStructSize = sizeof(OPENFILENAMEW);
ofn.hwndOwner = hwndOwner;
ofn.lpstrFilter = L"All Supported Files\0*.txt;*.bat;*.ps1;*.sh;*.json;*.xml;*.yaml;*.yml;*.ini;*.cfg;*.conf;*.log;*.md;*.py;*.js;*.ts;*.cpp;*.c;*.h;*.cs;*.java\0"
L"Text Files (*.txt)\0*.txt\0"
L"Script Files (*.bat;*.ps1;*.sh)\0*.bat;*.ps1;*.sh\0"
L"Config Files (*.json;*.xml;*.yaml;*.yml;*.ini;*.cfg;*.conf)\0*.json;*.xml;*.yaml;*.yml;*.ini;*.cfg;*.conf\0"
L"Code Files (*.py;*.js;*.ts;*.cpp;*.c;*.h;*.cs;*.java)\0*.py;*.js;*.ts;*.cpp;*.c;*.h;*.cs;*.java\0"
L"All Files (*.*)\0*.*\0";
ofn.lpstrFile = filePath;
ofn.nMaxFile = MAX_PATH;
ofn.lpstrTitle = L"Select file to send via MadPaster";
ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR;
if (GetOpenFileNameW(&ofn)) {
return std::wstring(filePath);
}
return L"";
}
// ============================================================================
// Input Injection Subsystem
// ============================================================================
namespace inject {
// RAII guard for high-resolution timer (1ms instead of ~15.6ms default)
struct TimerResolutionGuard {
TimerResolutionGuard() { timeBeginPeriod(1); }
~TimerResolutionGuard() { timeEndPeriod(1); }
};
// Information about detected remote client
struct RemoteClientInfo {
bool isRemote;
wchar_t className[256];
HWND hwnd;
DWORD threadId;
DWORD processId;
HKL keyboardLayout;
};
// Check if window class is a known remote client
bool IsKnownRemoteClass(const wchar_t* className) {
if (!className || !className[0]) return false;
for (int i = 0; REMOTE_WINDOW_CLASSES[i] != nullptr; i++) {
if (_wcsicmp(className, REMOTE_WINDOW_CLASSES[i]) == 0) {
return true;
}
}
return false;
}
// Detect if foreground window is a remote client
RemoteClientInfo DetectRemoteClient() {
RemoteClientInfo info = {};
info.hwnd = GetForegroundWindow();
if (!info.hwnd) {
return info;
}
// Get window class name
GetClassNameW(info.hwnd, info.className, 256);
// Get thread/process info
info.threadId = GetWindowThreadProcessId(info.hwnd, &info.processId);
// Get keyboard layout for VK mapping
info.keyboardLayout = GetKeyboardLayout(info.threadId);
// Check if this is a known remote class
info.isRemote = IsKnownRemoteClass(info.className);
return info;
}
// Send modifier reset fence - releases all modifier keys
void ResetModifiers() {
INPUT inputs[6] = {};
inputs[0].type = INPUT_KEYBOARD;
inputs[0].ki.wVk = VK_LSHIFT;
inputs[0].ki.dwFlags = KEYEVENTF_KEYUP;
inputs[1].type = INPUT_KEYBOARD;
inputs[1].ki.wVk = VK_RSHIFT;
inputs[1].ki.dwFlags = KEYEVENTF_KEYUP;
inputs[2].type = INPUT_KEYBOARD;
inputs[2].ki.wVk = VK_LCONTROL;
inputs[2].ki.dwFlags = KEYEVENTF_KEYUP;
inputs[3].type = INPUT_KEYBOARD;
inputs[3].ki.wVk = VK_RCONTROL;
inputs[3].ki.dwFlags = KEYEVENTF_KEYUP;
inputs[4].type = INPUT_KEYBOARD;
inputs[4].ki.wVk = VK_LMENU;
inputs[4].ki.dwFlags = KEYEVENTF_KEYUP;
inputs[5].type = INPUT_KEYBOARD;
inputs[5].ki.wVk = VK_RMENU;
inputs[5].ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(6, inputs, sizeof(INPUT));
}
// Forward declaration
void AppendCharacterInputs(std::vector<INPUT>& buffer, wchar_t c);
// VK/Scancode mapping result
struct VKMapping {
bool success;
BYTE vk;
WORD scancode;
bool needsShift;
};
// Map a character to VK code using VkKeyScanExW
// Only accepts "safe" mappings that require no modifiers or just Shift
// Rejects mappings that need Ctrl/Alt (would trigger shortcuts)
VKMapping MapCharacterToVK(wchar_t ch, HKL layout) {
VKMapping result = {};
SHORT vkResult = VkKeyScanExW(ch, layout);
if (vkResult == -1) {
// Character cannot be mapped to a VK code
return result;
}
BYTE vk = LOBYTE(vkResult);
BYTE modifiers = HIBYTE(vkResult);
// Only accept no modifiers (0) or Shift only (1)
// Reject Ctrl (2), Alt (4), or combinations
if (modifiers > 1) {
return result;
}
result.success = true;
result.vk = vk;
result.needsShift = (modifiers == 1);
// Get hardware scancode for VK
result.scancode = static_cast<WORD>(MapVirtualKeyW(vk, MAPVK_VK_TO_VSC));
return result;
}
// Append character using VK code with scancode
// Returns number of INPUT events added (2 for simple char, 4 with Shift)
int AppendVKCharacterInputs(std::vector<INPUT>& buffer, wchar_t ch, HKL layout) {
VKMapping mapping = MapCharacterToVK(ch, layout);
if (!mapping.success) {
return 0; // Caller should fall back to Unicode
}
int eventsAdded = 0;
// Press Shift if needed
if (mapping.needsShift) {
INPUT shiftDown = {};
shiftDown.type = INPUT_KEYBOARD;
shiftDown.ki.wVk = VK_SHIFT;
shiftDown.ki.wScan = static_cast<WORD>(MapVirtualKeyW(VK_SHIFT, MAPVK_VK_TO_VSC));
shiftDown.ki.dwFlags = KEYEVENTF_SCANCODE;
buffer.push_back(shiftDown);
eventsAdded++;
}
// Key down
INPUT down = {};
down.type = INPUT_KEYBOARD;
down.ki.wVk = mapping.vk;
down.ki.wScan = mapping.scancode;
down.ki.dwFlags = KEYEVENTF_SCANCODE;
buffer.push_back(down);
eventsAdded++;
// Key up
INPUT up = {};
up.type = INPUT_KEYBOARD;
up.ki.wVk = mapping.vk;
up.ki.wScan = mapping.scancode;
up.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP;
buffer.push_back(up);
eventsAdded++;
// Release Shift if pressed
if (mapping.needsShift) {
INPUT shiftUp = {};
shiftUp.type = INPUT_KEYBOARD;
shiftUp.ki.wVk = VK_SHIFT;
shiftUp.ki.wScan = static_cast<WORD>(MapVirtualKeyW(VK_SHIFT, MAPVK_VK_TO_VSC));
shiftUp.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP;
buffer.push_back(shiftUp);
eventsAdded++;
}
return eventsAdded;
}
// Append character using appropriate mode
// Returns true if character was added, false if skipped (should not happen)
bool AppendCharacterWithMode(std::vector<INPUT>& buffer, wchar_t ch,
InjectionMode mode, HKL layout) {
switch (mode) {
case InjectionMode::Unicode:
AppendCharacterInputs(buffer, ch);
return true;
case InjectionMode::VKScancode: {
int added = AppendVKCharacterInputs(buffer, ch, layout);
if (added == 0) {
// VK mapping failed - fall back to Unicode as last resort
AppendCharacterInputs(buffer, ch);
}
return true;
}
case InjectionMode::Hybrid: {
// Try VK first, fall back to Unicode
int added = AppendVKCharacterInputs(buffer, ch, layout);
if (added == 0) {
AppendCharacterInputs(buffer, ch);
}
return true;
}
case InjectionMode::Auto:
default:
// Auto mode should be resolved before calling this
// Default to Unicode
AppendCharacterInputs(buffer, ch);
return true;
}
}
// Flush accumulated INPUT events - loops until ALL events are sent
// Returns true if all events were sent, false on unrecoverable failure
// Optional eventsSent pointer to track total events successfully sent
bool FlushInputs(std::vector<INPUT>& buffer, size_t* eventsSent = nullptr) {
if (buffer.empty()) return true;
UINT total = static_cast<UINT>(buffer.size());
UINT offset = 0;
int consecutiveFailures = 0;
while (offset < total) {
UINT remaining = total - offset;
UINT sent = SendInput(remaining, buffer.data() + offset, sizeof(INPUT));
if (sent > 0) {
offset += sent;
if (eventsSent) *eventsSent += sent;
consecutiveFailures = 0;
} else {
// Complete failure - yield and retry
consecutiveFailures++;
if (consecutiveFailures >= MAX_RETRY_COUNT) {
buffer.clear();
return false;
}
Sleep(1); // Real yield - allows target to drain input queue
}
}
buffer.clear();
return true;
}
// Forward declarations for pacing
struct DiagnosticState;
// Pacing configuration for injection
struct PacingConfig {
PacingStrategy strategy;
int perEventDelayMs;
int perCharDelayMs;
int lineStartGuardChars;
int lineStartGuardMs;
int baseKeystrokeDelayMs; // From UI setting
};
// Get default pacing config based on target type
PacingConfig GetDefaultPacingConfig(bool isRemote) {
PacingConfig config = {};
config.perEventDelayMs = PER_EVENT_DELAY_MS;
config.perCharDelayMs = PER_CHAR_DELAY_MS;
config.lineStartGuardChars = LINE_START_GUARD_CHARS;
config.lineStartGuardMs = LINE_START_GUARD_MS;
config.baseKeystrokeDelayMs = g_app.keystrokeDelayMs;
if (isRemote) {
config.strategy = PacingStrategy::PerCharacter;
} else {
config.strategy = PacingStrategy::Burst;
}
return config;
}
// Flush with per-event pacing - sends events one at a time with delays
// Returns number of events successfully sent
size_t FlushInputsWithPacing(std::vector<INPUT>& buffer, const PacingConfig& config,
DiagnosticState* diag) {
if (buffer.empty()) return 0;
size_t sent = 0;
int consecutiveFailures = 0;
for (size_t i = 0; i < buffer.size(); i++) {
UINT result = SendInput(1, &buffer[i], sizeof(INPUT));
if (result > 0) {
sent++;
consecutiveFailures = 0;
// Per-event delay
if (config.strategy == PacingStrategy::PerEvent && config.perEventDelayMs > 0) {
Sleep(config.perEventDelayMs);
}
} else {
consecutiveFailures++;
if (consecutiveFailures >= MAX_RETRY_COUNT) {
break; // Abort on repeated failures
}
Sleep(1);
i--; // Retry this event
}
}
buffer.clear();
return sent;
}
// Append character using KEYEVENTF_UNICODE (no modifiers involved)
void AppendCharacterInputs(std::vector<INPUT>& buffer, wchar_t c) {
INPUT down = {};
down.type = INPUT_KEYBOARD;
down.ki.wScan = c;
down.ki.dwFlags = KEYEVENTF_UNICODE;
buffer.push_back(down);
INPUT up = {};
up.type = INPUT_KEYBOARD;
up.ki.wScan = c;
up.ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP;
buffer.push_back(up);
}
// Send Enter key using hardware scancode for maximum compatibility
// Unicode CR/LF doesn't create line breaks in Scintilla-based editors
// Using KEYEVENTF_SCANCODE forces hardware-level input that Scintilla handles correctly
void SendEnterKey() {
INPUT inputs[2] = {};
// Key down - use scancode mode for hardware-level simulation
inputs[0].type = INPUT_KEYBOARD;
inputs[0].ki.wVk = 0; // Must be 0 when using KEYEVENTF_SCANCODE
inputs[0].ki.wScan = 0x1C; // Hardware scan code for Enter key
inputs[0].ki.dwFlags = KEYEVENTF_SCANCODE;
// Key up
inputs[1].type = INPUT_KEYBOARD;
inputs[1].ki.wVk = 0;
inputs[1].ki.wScan = 0x1C;
inputs[1].ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP;
// Send both events atomically
SendInput(2, inputs, sizeof(INPUT));
}
// Drain the input queue by yielding CPU time repeatedly
// This ensures the target app has time to process pending input before we continue
void DrainInputQueue() {
// Multiple yields with longer sleeps to let the target process its message queue
// SwitchToThread yields to any ready thread, Sleep(1) allows scheduler to run others
for (int i = 0; i < 5; i++) {
SwitchToThread();
Sleep(2);
}
}
// Get process ID of foreground window
DWORD GetForegroundProcessId() {
HWND fg = GetForegroundWindow();
if (!fg) return 0;
DWORD pid = 0;
GetWindowThreadProcessId(fg, &pid);
return pid;
}
// Wait for target process to become idle (finished processing input)
// Returns true if idle or on error, false on timeout
bool WaitForTargetIdle(DWORD pid, DWORD maxWaitMs) {
if (pid == 0) return true;
HANDLE hProcess = OpenProcess(SYNCHRONIZE, FALSE, pid);
if (!hProcess) return true; // Can't open = assume ready
DWORD result = WaitForInputIdle(hProcess, maxWaitMs);
CloseHandle(hProcess);
// 0 = success (idle), WAIT_TIMEOUT = timeout, WAIT_FAILED = error
return (result != WAIT_TIMEOUT);
}
// Diagnostic state for injection debugging
struct DiagnosticState {
size_t totalEventsAttempted;
size_t totalEventsSent;
size_t totalEventsFailed;
size_t totalCharsSent;
size_t totalCharsRequested;
std::vector<std::pair<DWORD, std::wstring>> foregroundChanges;
std::vector<std::wstring> errors;
DWORD startTime;
DWORD endTime;
// Context info
std::wstring injectionModeName;
std::wstring targetClassName;
bool targetIsRemote;
DiagnosticState() : totalEventsAttempted(0), totalEventsSent(0),
totalEventsFailed(0), totalCharsSent(0),
totalCharsRequested(0), startTime(0), endTime(0),
targetIsRemote(false) {}
void RecordForegroundChange(HWND hwnd) {
wchar_t className[256] = {};
if (hwnd) GetClassNameW(hwnd, className, 256);
foregroundChanges.push_back({GetTickCount(), className});
}
void RecordError(const std::wstring& error) {
errors.push_back(error);
}
std::wstring GetSummary(bool forMessageBox = false) {
std::wstring summary;
std::wstring nl = forMessageBox ? L"\n" : L"\r\n";
if (!forMessageBox) {
// Add timestamp for log file
SYSTEMTIME st;
GetLocalTime(&st);
wchar_t timestamp[64];
swprintf_s(timestamp, L"[%04d-%02d-%02d %02d:%02d:%02d]",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
summary += timestamp;
summary += nl;
}
summary += L"MadPaster Injection Report" + nl;
summary += L"─────────────────────────────" + nl;
// Target info
summary += L"Target: " + targetClassName;
if (targetIsRemote) summary += L" (Remote)";
summary += nl;
summary += L"Mode: " + injectionModeName + nl;
summary += nl;
// Results
summary += L"Characters: " + std::to_wstring(totalCharsSent) + L" / " +
std::to_wstring(totalCharsRequested);
if (totalCharsSent == totalCharsRequested) {
summary += L" ✓";
} else {
summary += L" (incomplete)";
}
summary += nl;
summary += L"Events: " + std::to_wstring(totalEventsSent) + L" / " +
std::to_wstring(totalEventsAttempted) + L" sent" + nl;
DWORD duration = endTime - startTime;
summary += L"Duration: " + std::to_wstring(duration) + L" ms";
if (duration > 0 && totalCharsSent > 0) {
double cps = (double)totalCharsSent * 1000.0 / (double)duration;
wchar_t cpsStr[32];
swprintf_s(cpsStr, L" (%.1f chars/sec)", cps);
summary += cpsStr;
}
summary += nl;
// Issues
if (!foregroundChanges.empty() || !errors.empty()) {
summary += nl + L"Issues:" + nl;
if (!foregroundChanges.empty()) {
summary += L" • Focus changed " + std::to_wstring(foregroundChanges.size()) +
L" time(s) during injection" + nl;
}
for (const auto& err : errors) {
summary += L" • " + err + nl;
}
}
return summary;
}
};
// Optional keyboard hook for diagnostic verification
// Counts how many injected events actually reach the system
static HHOOK g_diagHook = nullptr;
static volatile LONG g_hookEventCount = 0;
LRESULT CALLBACK DiagnosticKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode >= 0) {
KBDLLHOOKSTRUCT* pKbd = reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam);
// Count injected events (LLKHF_INJECTED flag)
if (pKbd->flags & LLKHF_INJECTED) {
InterlockedIncrement(&g_hookEventCount);
}
}
return CallNextHookEx(g_diagHook, nCode, wParam, lParam);
}
bool InstallDiagnosticHook() {
if (g_diagHook) return true; // Already installed
g_hookEventCount = 0;
g_diagHook = SetWindowsHookExW(WH_KEYBOARD_LL, DiagnosticKeyboardProc,
GetModuleHandleW(nullptr), 0);
return (g_diagHook != nullptr);
}
void RemoveDiagnosticHook() {
if (g_diagHook) {
UnhookWindowsHookEx(g_diagHook);
g_diagHook = nullptr;
}
}
size_t GetHookEventCount() {
return static_cast<size_t>(InterlockedExchangeAdd(&g_hookEventCount, 0));
}
void ResetHookEventCount() {
InterlockedExchange(&g_hookEventCount, 0);
}
// Low-level keyboard hook for abort detection
// Intercepts ESC at system level, works even when Citrix/RDP has focus
static HHOOK g_abortHook = nullptr;
static volatile LONG g_abortRequested = 0;
LRESULT CALLBACK AbortKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode >= 0 && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN)) {
KBDLLHOOKSTRUCT* pKbd = reinterpret_cast<KBDLLHOOKSTRUCT*>(lParam);
// Check for ESC key (not injected by us)
if (pKbd->vkCode == VK_ESCAPE && !(pKbd->flags & LLKHF_INJECTED)) {
InterlockedExchange(&g_abortRequested, 1);
}
}
return CallNextHookEx(g_abortHook, nCode, wParam, lParam);
}
bool InstallAbortHook() {
if (g_abortHook) return true; // Already installed
g_abortRequested = 0;
g_abortHook = SetWindowsHookExW(WH_KEYBOARD_LL, AbortKeyboardProc,
GetModuleHandleW(nullptr), 0);
return (g_abortHook != nullptr);
}
void RemoveAbortHook() {
if (g_abortHook) {
UnhookWindowsHookEx(g_abortHook);
g_abortHook = nullptr;
}
g_abortRequested = 0;
}
bool IsAbortRequested() {
return (InterlockedExchangeAdd(&g_abortRequested, 0) != 0);
}
void ResetAbortFlag() {
InterlockedExchange(&g_abortRequested, 0);
}
} // namespace inject
// ============================================================================
// Keyboard Simulation
// ============================================================================
// Progress callback type for injection progress reporting
typedef void (*ProgressCallback)(size_t current, size_t total);
// Extended injection function with mode and pacing configuration
size_t sendTextToWindowEx(const std::wstring& text, InjectionMode mode,
const inject::PacingConfig& config,