-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInput.cs
More file actions
795 lines (687 loc) · 37.3 KB
/
Input.cs
File metadata and controls
795 lines (687 loc) · 37.3 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace WinUtilities {
/// <summary>Specifies what method is used to send the input</summary>
public enum SendMode {
/// <summary>Uses the windows SendInput API. Fast and reliable, but rejected by certain applications.</summary>
Input,
/// <summary>Uses the event API. Slower and less reliable, but more compatible with some applications.</summary>
Event,
/// <summary>Sends key messages directly. Least reliable, but might be able to send input to background windows directly.</summary>
Control
}
/// <summary>Class for sending native windows input</summary>
public static class Input {
private static readonly uint pid = (uint)Process.GetCurrentProcess().Id;
/// <summary>The text character for parsing special input when sending text. Default is '['.</summary>
public static char ParseOpen { get; } = '[';
/// <summary>The text character for parsing special input when sending text. Default is ']'.</summary>
public static char ParseClose { get; } = ']';
private const int keydownflag = 0x00000001;
private const int keyupflag = unchecked((int)0xC0000001);
/// <summary>Set to true to force the SCANCODE flag</summary>
public static bool ForceScan { get; set; } = false;
#region mappings
private static Dictionary<KeyState, WinAPI.MOUSEEVENTF> MouseMap { get; } = new Dictionary<KeyState, WinAPI.MOUSEEVENTF> {
{ new KeyState(Key.LButton, true), WinAPI.MOUSEEVENTF.LEFTDOWN },
{ new KeyState(Key.LButton, false), WinAPI.MOUSEEVENTF.LEFTUP },
{ new KeyState(Key.RButton, true), WinAPI.MOUSEEVENTF.RIGHTDOWN },
{ new KeyState(Key.RButton, false), WinAPI.MOUSEEVENTF.RIGHTUP },
{ new KeyState(Key.MButton, true), WinAPI.MOUSEEVENTF.MIDDLEDOWN },
{ new KeyState(Key.MButton, false), WinAPI.MOUSEEVENTF.MIDDLEUP }
};
/// <summary>List of short modifier symbols used in parsed string input</summary>
public static Dictionary<char, Key> ShortModifiers { get; } = new Dictionary<char, Key> {
{ '+', Key.RShift },
{ '!', Key.LAlt },
{ '#', Key.RWin },
{ '^', Key.RCtrl }
};
/// <summary>Retrieve the Key equivalent from a <see cref="WM"/> message</summary>
public static KeyState FromMouseEvent(WM message, int data = 0) {
switch (message) {
case WM.LBUTTONDOWN: {
return new KeyState(Key.LButton, true);
}
case WM.LBUTTONUP: {
return new KeyState(Key.LButton, false);
}
case WM.LBUTTONDBLCLK: {
return new KeyState(Key.LButton, true);
}
case WM.RBUTTONDOWN: {
return new KeyState(Key.RButton, true);
}
case WM.RBUTTONUP: {
return new KeyState(Key.RButton, false);
}
case WM.RBUTTONDBLCLK: {
return new KeyState(Key.RButton, true);
}
case WM.MBUTTONDOWN: {
return new KeyState(Key.MButton, true);
}
case WM.MBUTTONUP: {
return new KeyState(Key.MButton, false);
}
case WM.MBUTTONDBLCLK: {
return new KeyState(Key.MButton, true);
}
case WM.MOUSEWHEEL: {
var key = data >> 16 > 0 ? Key.WheelUp : Key.WheelDown;
return new KeyState(key, true);
}
case WM.MOUSEHWHEEL: {
var key = data >> 16 > 0 ? Key.WheelRight : Key.WheelLeft;
return new KeyState(key, true);
}
case WM.XBUTTONDOWN: {
data >>= 16;
if (data == 1) {
return new KeyState(Key.XButton1, true);
} else {
return new KeyState(Key.XButton2, true);
}
}
case WM.XBUTTONUP: {
data >>= 16;
if (data == 1) {
return new KeyState(Key.XButton1, false);
} else {
return new KeyState(Key.XButton2, false);
}
}
case WM.XBUTTONDBLCLK: {
data >>= 16;
if (data == 1) {
return new KeyState(Key.XButton1, true);
} else {
return new KeyState(Key.XButton2, true);
}
}
case WM.MOUSEMOVE: {
return new KeyState(Key.MouseMove, true);
}
}
throw new Exception("Unknown mouse input" + message);
}
#endregion
#region user methods
/// <summary>Get the logical state of a key. Does not differentiate between extended and non-extended keys</summary>
public static bool GetKeyState(Key key) => WinAPI.GetAsyncKeyState(key.AsVirtualKey()) < 0;
/// <summary>Check toggle state of CapsLock/NumLock/ScrollLock</summary>
/// <exception cref="ArgumentException"></exception>
public static bool GetToggleState(Key key) {
if (key != Key.Numlock && key != Key.CapsLock && key != Key.ScrollLock)
throw new ArgumentException("Given key is not a toggleable key");
return (WinAPI.GetKeyState(key.AsVirtualKey()) & 0x0001) != 0;
}
/// <summary>Send Ctrl + V to the current window</summary>
public static void Paste() => Send("[^][v]");
/// <summary>Send Ctrl + C to the current window</summary>
public static void Copy() => Send("[^][c]");
/// <summary>Send text input.</summary>
/// <remarks>
/// The <paramref name="text"/> is parsed for special input when between [ and ]. This behaviour can be escaped with [[ and ]].
/// <para/>Any entity, a single character or a special input [], can be preceded with a modifier set like: [+!][Enter] -> Shift + Alt + Enter -OR- [#]p -> Win + P.
/// <para/>The modifiers supported are RShift(+), RCtrl(^), LAlt(!) or RWin(#).
/// <para/>The general layout of normal special input is [key up/down (amount) text] where anything besides the key can be omitted or included as needed.
/// <para/>Specifying up or down will send only that event, instead of sending both down and up events.
/// <para/>Specifying 'text' in the special input sends the 'key' as text instead. For example [Enter 5] sends the Enter key five times but [Enter 5 text] sends the text 'Enter' 5 times.
/// <para/>While using 'text' the 'key' part must not contain any spaces. This makes sending long text difficult, but is useful in sending a specific symbol many times, like [§ 10 text].
/// </remarks>
public static async void Send(string text, SendMode mode) {
if (text == null)
return;
var inputs = ParseDelays(text);
for (int i = 0; i < inputs.Item1.Count; i++) {
if (!string.IsNullOrEmpty(inputs.Item1[i])) {
if (mode == SendMode.Input) {
SendText(inputs.Item1[i]);
} else if (mode == SendMode.Event) {
SendEvent(inputs.Item1[i]);
} else {
SendControl(Window.Active, inputs.Item1[i]);
}
}
if (i < inputs.Item2.Count) {
await Task.Delay(inputs.Item2[i]);
}
}
}
/// <summary>Send raw text input</summary>
public static void SendRaw(string text, SendMode mode) {
if (text == null)
return;
if (mode == SendMode.Input) {
SendRaw(text);
} else if (mode == SendMode.Event) {
SendEventRaw(text);
} else {
SendControlRaw(Window.Active, text);
}
}
/// <summary>Send char input</summary>
public static void Send(char c, SendMode mode) {
if (mode == SendMode.Input) {
Send(c);
} else if (mode == SendMode.Event) {
SendEvent(c);
} else {
SendControl(Window.Active, c);
}
}
#region send input
/// <summary>Send text in Input mode.</summary>
/// <remarks>
/// The <paramref name="text"/> is parsed for special input when between [ and ]. This behaviour can be escaped with [[ and ]].
/// <para/>Any entity, a single character or a special input [], can be preceded with a modifier set like: [+!][Enter] -> Shift + Alt + Enter -OR- [#]p -> Win + P.
/// <para/>The modifiers supported are RShift(+), RCtrl(^), LAlt(!) or RWin(#).
/// <para/>The general layout of normal special input is [key up/down (amount) text] where anything besides the key can be omitted or included as needed.
/// <para/>Specifying up or down will send only that event, instead of sending both down and up events.
/// <para/>Specifying 'text' in the special input sends the 'key' as text instead. For example [Enter 5] sends the Enter key five times but [Enter 5 text] sends the text 'Enter' 5 times.
/// <para/>While using 'text' the 'key' part must not contain any spaces. This makes sending long text difficult, but is useful in sending a specific symbol many times, like [§ 10 text].
/// </remarks>
public static void Send(string text) => Send(text, SendMode.Input);
private static bool SendText(string text) => SendInput(ToInputList(text));
/// <summary>Send chars in Input mode</summary>
public static bool Send(params char[] chars) => SendInput(chars.SelectMany(c => GetCharInput(c)).ToArray());
/// <summary>Send keys in Input mode</summary>
public static bool Send(params Key[] keys) => SendInput(ToInputList(keys));
/// <summary>Send down keys in Input mode</summary>
public static bool SendDown(params Key[] keys) => SendInput(ToInputList(keys, true));
/// <summary>Send up keys in Input mode</summary>
public static bool SendUp(params Key[] keys) => SendInput(ToInputList(keys, false));
/// <summary>Send raw text in Input mode. This string is not parsed in any way before sending.</summary>
public static bool SendRaw(string text) => SendInput(text.SelectMany(c => GetCharInput(c)).ToArray());
/// <summary>Send a scroll event in Input mode. Uses raw scroll values, 120 for default downward scroll.</summary>
public static bool Scroll(int amount) => SendInput(GetMouseInputScroll(amount >= 0 ? Key.WheelDown : Key.WheelUp, Math.Abs(amount)));
/// <summary>Send relative mouse movement in Input mode</summary>
public static bool MouseMoveRelative(int dx, int dy) => SendInput(GetMouseInputMove(dx, dy));
/// <summary>Send lenghtened key presses that are easily recognized by game like applications in Input mode. Up event is delayed by 20 ms.</summary>
public static async Task SendGame(params Key[] keys) => await SendGame(20, keys);
/// <summary>Send lenghtened key presses that are easily recognized by game like applications in Input mode</summary>
/// <param name="delay">The amount of time before the up event is sent</param>
/// <param name="keys">The keys to send as input</param>
public static async Task SendGame(int delay, params Key[] keys) {
SendInput(keys.Select(k => GetInput(k, true)).ToArray());
await Task.Delay(delay);
SendInput(keys.Select(k => GetInput(k, false)).ToArray());
}
/// <summary>Send a series of lenghtened key presses. Tries to emulate typing using key presses. Sends real keys instead of unicode.</summary>
public static async Task SendGameText(int delay, string text) {
Key[] keys = StringToKeys(text);
foreach (Key key in keys) {
await SendEventGame(delay, key);
await Task.Delay(delay);
}
}
#endregion
#region send event
/// <summary>Send text in Event mode.</summary>
/// <remarks>
/// The <paramref name="text"/> is parsed for special input when between [ and ]. This behaviour can be escaped with [[ and ]].
/// <para/>Any entity, a single character or a special input [], can be preceded with a modifier set like: [+!][Enter] -> Shift + Alt + Enter -OR- [#]p -> Win + P.
/// <para/>The modifiers supported are RShift(+), RCtrl(^), LAlt(!) or RWin(#).
/// <para/>The general layout of normal special input is [key up/down (amount) text] where anything besides the key can be omitted or included as needed.
/// <para/>Specifying up or down will send only that event, instead of sending both down and up events.
/// <para/>Specifying 'text' in the special input sends the 'key' as text instead. For example [Enter 5] sends the Enter key five times but [Enter 5 text] sends the text 'Enter' 5 times.
/// <para/>While using 'text' the 'key' part must not contain any spaces. This makes sending long text difficult, but is useful in sending a specific symbol many times, like [§ 10 text].
/// </remarks>
public static void SendEvent(string text) => SendEvent(ToInputList(text));
/// <summary>Send chars in Event mode</summary>
public static void SendEvent(params char[] chars) => SendEvent(chars.SelectMany(c => GetCharInput(c)).ToArray());
/// <summary>Send keys in Event mode</summary>
public static void SendEvent(params Key[] keys) => SendEvent(ToInputList(keys));
/// <summary>Send down keys in Event mode</summary>
public static void SendEventDown(params Key[] keys) => SendEvent(ToInputList(keys, true));
/// <summary>Send up keys in Event mode</summary>
public static void SendEventUp(params Key[] keys) => SendEvent(ToInputList(keys, false));
/// <summary>Send raw text in Event mode. This string is not parsed in any way before sending.</summary>
public static void SendEventRaw(string text) => SendEvent(text.SelectMany(c => GetCharInput(c)).ToArray());
/// <summary>Send lenghtened key presses that are easily recognized by game like applications in Event mode. Up event is delayed by 20 ms.</summary>
public static async Task SendEventGame(params Key[] keys) => await SendEventGame(20, keys);
/// <summary>Send lenghtened key presses that are easily recognized by game like applications in Event mode</summary>
/// <param name="delay">The amount of time before the up event is sent</param>
/// <param name="keys">The keys to send as input</param>
public static async Task SendEventGame(int delay, params Key[] keys) {
SendInput(keys.Select(k => GetInput(k, true)).ToArray());
await Task.Delay(delay);
SendInput(keys.Select(k => GetInput(k, false)).ToArray());
}
/// <summary>Send a series of lenghtened key presses. Tries to emulate typing using key presses. Sends real keys instead of unicode.</summary>
public static async Task SendEventGameText(int delay, string text) {
Key[] keys = StringToKeys(text);
foreach (Key key in keys) {
await SendEventGame(delay, key);
await Task.Delay(delay);
}
}
#endregion
#region send control
/// <summary>Send text in Control mode.</summary>
/// <remarks>
/// The <paramref name="text"/> is parsed for special input when between [ and ]. This behaviour can be escaped with [[ and ]].
/// <para/>Any entity, a single character or a special input [], can be preceded with a modifier set like: [+!][Enter] -> Shift + Alt + Enter -OR- [#]p -> Win + P.
/// <para/>The modifiers supported are RShift(+), RCtrl(^), LAlt(!) or RWin(#).
/// <para/>The general layout of normal special input is [key up/down (amount) text] where anything besides the key can be omitted or included as needed.
/// <para/>Specifying up or down will send only that event, instead of sending both down and up events.
/// <para/>Specifying 'text' in the special input sends the 'key' as text instead. For example [Enter 5] sends the Enter key five times but [Enter 5 text] sends the text 'Enter' 5 times.
/// <para/>While using 'text' the 'key' part must not contain any spaces. This makes sending long text difficult, but is useful in sending a specific symbol many times, like [§ 10 text].
/// </remarks>
public static void SendControl(Window window, string text) => SendControl(window, ToInputList(text));
/// <summary>Send chars in Control mode</summary>
public static void SendControl(Window window, params char[] chars) => SendControlText(window, chars);
/// <summary>Send keys in Control mode</summary>
public static void SendControl(Window window, params Key[] keys) => SendControl(window, ToInputList(keys));
/// <summary>Send down keys in Control mode</summary>
public static void SendControlDown(Window window, params Key[] keys) => SendControl(window, ToInputList(keys, true));
/// <summary>Send up keys in Control mode</summary>
public static void SendControlUp(Window window, params Key[] keys) => SendControl(window, ToInputList(keys, false));
/// <summary>Send raw text in Control mode. This string is not parsed in any way before sending.</summary>
public static void SendControlRaw(Window window, string text) => SendControlText(window, text.ToArray());
#endregion
#endregion
#region public helpers
/// <summary>Map a key name to a <see cref="Key"/></summary>
public static Key StringToKey(string keyName) {
keyName = Regex.Replace(keyName, "Control", "Ctrl", RegexOptions.IgnoreCase);
keyName = Regex.Replace(keyName, @"^\d$", "D" + keyName);
keyName = keyName.Replace(" ", "Space");
if (Enum.TryParse(keyName, true, out Key key))
return key;
throw new Exception($"Key named {keyName} not found");
}
/// <summary>Map a character to a <see cref="Key"/></summary>
public static Key CharToKey(char c) {
return StringToKey(c.ToString());
}
/// <summary>Map a string into a series of <see cref="Key"/>s</summary>
public static Key[] StringToKeys(string s) {
return s.Select(c => CharToKey(c)).ToArray();
}
#endregion
#region helper
/// <summary>Send input with the SendInput API</summary>
private static bool SendInput(params WinAPI.INPUT[] inputs) {
if (inputs.Length < 1)
return true;
return WinAPI.SendInput((uint)inputs.Length, inputs, WinAPI.INPUT.Size) != 0;
}
/// <summary>Send input with the event API</summary>
private static void SendEvent(params WinAPI.INPUT[] inputs) {
if (inputs.Length < 1)
return;
foreach (var input in inputs) {
if (input.type == WinAPI.InputType.Keyboard) {
var kInput = input.union.keyboard;
WinAPI.keybd_event(kInput.vk, kInput.sc, kInput.flags, kInput.extraInfo);
} else if (input.type == WinAPI.InputType.Mouse) {
var mInput = input.union.mouse;
WinAPI.mouse_event(mInput.flags, mInput.dx, mInput.dy, mInput.mouseData, mInput.extraInfo);
}
}
}
#region control send
/// <summary>Send input directly to windows</summary>
private static void SendControl(Window window, params WinAPI.INPUT[] inputs) {
foreach (var input in inputs) {
if (input.type == WinAPI.InputType.Mouse) {
SendControlMouse(window, input.union.mouse);
} else {
SendControlKeyboard(window, input.union.keyboard);
}
}
}
private static void SendControlKeyboard(Window window, WinAPI.KEYBDINPUT input) {
int scan = (int)input.sc | (input.flags.HasFlag(WinAPI.KEYEVENTF.EXTENDEDKEY) ? 1 << 24 : 0);
if (input.flags.HasFlag(WinAPI.KEYEVENTF.UNICODE)) {
if (!input.flags.HasFlag(WinAPI.KEYEVENTF.KEYUP))
window.PostMessage(WM.CHAR, (int)input.sc, 0);
} else if (!input.flags.HasFlag(WinAPI.KEYEVENTF.KEYUP))
window.PostMessage(WM.KEYDOWN, (int)input.vk, scan | keydownflag);
else
window.PostMessage(WM.KEYUP, (int)input.vk, scan | keyupflag);
}
private static void SendControlMouse(Window window, WinAPI.MOUSEINPUT input) {
WM message;
int wParam = 0;
int lParam = 0;
if (input.flags.HasFlag(WinAPI.MOUSEEVENTF.LEFTDOWN)) {
message = WM.LBUTTONDOWN;
wParam = 1;
lParam = Mouse.Position.SetRelative(window.ClientArea).AsValue;
} else if (input.flags.HasFlag(WinAPI.MOUSEEVENTF.LEFTUP)) {
message = WM.LBUTTONUP;
lParam = Mouse.Position.SetRelative(window.ClientArea).AsValue;
} else if (input.flags.HasFlag(WinAPI.MOUSEEVENTF.RIGHTDOWN)) {
message = WM.RBUTTONDOWN;
wParam = 2;
lParam = Mouse.Position.SetRelative(window.ClientArea).AsValue;
} else if (input.flags.HasFlag(WinAPI.MOUSEEVENTF.RIGHTUP)) {
message = WM.RBUTTONUP;
lParam = Mouse.Position.SetRelative(window.ClientArea).AsValue;
} else if (input.flags.HasFlag(WinAPI.MOUSEEVENTF.MIDDLEDOWN)) {
message = WM.MBUTTONDOWN;
wParam = 16;
lParam = Mouse.Position.SetRelative(window.ClientArea).AsValue;
} else if (input.flags.HasFlag(WinAPI.MOUSEEVENTF.MIDDLEUP)) {
message = WM.MBUTTONUP;
lParam = Mouse.Position.SetRelative(window.ClientArea).AsValue;
} else if (input.flags.HasFlag(WinAPI.MOUSEEVENTF.MOVE) || input.flags.HasFlag(WinAPI.MOUSEEVENTF.MOVE_NOCOALESCE)) {
message = WM.MOUSEMOVE;
lParam = Coord.Zero.AsValue;
} else if (input.flags.HasFlag(WinAPI.MOUSEEVENTF.WHEEL)) {
message = WM.MOUSEWHEEL;
wParam = input.mouseData << 16;
} else if (input.flags.HasFlag(WinAPI.MOUSEEVENTF.HWHEEL)) {
message = WM.MOUSEHWHEEL;
wParam = input.mouseData << 16;
} else if (input.flags.HasFlag(WinAPI.MOUSEEVENTF.XDOWN)) {
message = WM.XBUTTONDOWN;
wParam = input.mouseData << 16;
lParam = input.mouseData == 1 ? 32 : 64;
} else if (input.flags.HasFlag(WinAPI.MOUSEEVENTF.XUP)) {
message = WM.XBUTTONUP;
wParam = input.mouseData << 16;
} else {
throw new Exception("Illegal mouse input event");
}
window.PostMessage(message, wParam, lParam);
}
private static void SendControlText(Window window, params char[] chars) {
foreach (char c in chars) {
if (c == '\r') continue;
if (c == '\n') SendControl(window, Key.Enter);
else window.PostMessage(WM.CHAR, c, 0);
}
}
#endregion
/// <summary>Build a keyboard input object with given data</summary>
private static WinAPI.INPUT RawKeyboardInput(WinAPI.KEYEVENTF flags, Key key = 0, ScanCode sc = 0) {
if (ForceScan)
flags |= WinAPI.KEYEVENTF.SCANCODE;
return new WinAPI.INPUT {
type = WinAPI.InputType.Keyboard,
union = {
keyboard = new WinAPI.KEYBDINPUT {
vk = key == 0 ? 0 : key.AsVirtualKey(),
sc = sc != 0 ? sc : key.AsScanCode(),
flags = flags,
time = 0,
extraInfo = (UIntPtr) pid
}
}
};
}
/// <summary>Build a mouse input object with given data</summary>
private static WinAPI.INPUT RawMouseInput(WinAPI.MOUSEEVENTF flags, int data = 0, int dx = 0, int dy = 0) {
return new WinAPI.INPUT {
type = WinAPI.InputType.Mouse,
union = {
mouse = new WinAPI.MOUSEINPUT {
dx = dx,
dy = dy,
mouseData = data,
flags = flags,
time = 0,
extraInfo = (UIntPtr) pid
}
}
};
}
/// <summary>Get a key as input</summary>
private static WinAPI.INPUT GetInput(Key key, bool state) {
if (key.IsMouse())
return GetMouseInput(key, state);
return GetKeyboardInput(key, state);
}
/// <summary>Get a keyboard event as input</summary>
private static WinAPI.INPUT GetKeyboardInput(Key key, bool state) {
var flags = key.IsExtended() ? WinAPI.KEYEVENTF.EXTENDEDKEY : 0;
if (!state) flags |= WinAPI.KEYEVENTF.KEYUP;
return RawKeyboardInput(flags, key);
}
/// <summary>Get a mouse event as input</summary>
private static WinAPI.INPUT GetMouseInput(Key key, bool state) {
if (key.IsScroll()) {
if (!state)
throw new Exception("Scroll keys cannot be released.");
return GetMouseInputScroll(key, 120);
} else if (key == Key.XButton1 || key == Key.XButton2) {
return GetMouseInputX(key, state);
}
var flags = MouseMap[new KeyState(key, state)];
return RawMouseInput(flags);
}
/// <summary>Get a mouse extra button event as input</summary>
private static WinAPI.INPUT GetMouseInputX(Key key, bool state) {
var flags = state ? WinAPI.MOUSEEVENTF.XDOWN : WinAPI.MOUSEEVENTF.XUP;
var data = key == Key.XButton1 ? 1 : 2;
return RawMouseInput(flags, data);
}
/// <summary>Get a scroll event as input</summary>
/// <remarks>120 is the default speed of a normal scroll event</remarks>
private static WinAPI.INPUT GetMouseInputScroll(Key key, int amount) {
if (amount < 0) {
throw new ArgumentException("Scroll amount cannot be negative.");
}
WinAPI.MOUSEEVENTF flags;
if (key == Key.WheelLeft) {
flags = WinAPI.MOUSEEVENTF.HWHEEL;
amount *= -1;
} else if (key == Key.WheelRight) {
flags = WinAPI.MOUSEEVENTF.HWHEEL;
} else if (key == Key.WheelUp) {
flags = WinAPI.MOUSEEVENTF.WHEEL;
} else if (key == Key.WheelDown) {
flags = WinAPI.MOUSEEVENTF.WHEEL;
amount *= -1;
} else {
throw new ArgumentException("The provided key must be a scroll key.");
}
return RawMouseInput(flags, amount);
}
/// <summary>Get a mouse move as input</summary>
private static WinAPI.INPUT GetMouseInputMove(int dx, int dy, bool coalesce = true) {
var flags = coalesce ? WinAPI.MOUSEEVENTF.MOVE : WinAPI.MOUSEEVENTF.MOVE_NOCOALESCE;
return RawMouseInput(flags, 0, dx, dy);
}
/// <summary>Get an input object from a character</summary>
private static WinAPI.INPUT[] GetCharInput(char c) {
ScanCode scan = (ScanCode)c;
var flags = WinAPI.KEYEVENTF.UNICODE;
if (scan.IsExtended()) flags |= WinAPI.KEYEVENTF.EXTENDEDKEY;
var down = RawKeyboardInput(flags, sc: scan);
var up = RawKeyboardInput(flags | WinAPI.KEYEVENTF.KEYUP, sc: scan);
return new WinAPI.INPUT[] { down, up };
}
/// <summary>Turn an array of keys into inputs</summary>
private static WinAPI.INPUT[] ToInputList(Key[] keys, bool? state = null) {
List<WinAPI.INPUT> input = new List<WinAPI.INPUT>();
foreach (Key key in keys) {
if (state is bool bstate) {
if (bstate)
input.Add(GetInput(key, true));
else if (!key.IsStateless())
input.Add(GetInput(key, false));
} else {
input.Add(GetInput(key, true));
if (!key.IsStateless()) {
input.Add(GetInput(key, false));
}
}
}
return input.ToArray();
}
#region string input parsing
/// <summary></summary>
public static (List<string>, List<int>) ParseDelays(string textInput) {
List<int> delays = new List<int>();
List<string> inputs = new List<string>();
var match = Regex.Match(textInput, @"(?<=\[)\d+(?=ms\])", RegexOptions.IgnoreCase);
foreach (Capture item in match.Captures)
delays.Add(int.Parse(item.Value));
var splits = Regex.Split(textInput, @"\[\d+ms\]", RegexOptions.IgnoreCase);
inputs = splits.ToList();
return (inputs, delays);
}
/// <summary>Parse a string to a list of inputs</summary>
private static WinAPI.INPUT[] ToInputList(string s) {
if (s == null)
return new WinAPI.INPUT[0];
s = Regex.Replace(s, @"\r?\n|\r\n?", "[Enter]");
char[] chars = s.ToCharArray();
List<WinAPI.INPUT> res = new List<WinAPI.INPUT>();
var pendingModifiers = new List<Key>();
for (int i = 0; i < chars.Length; i++) {
// Parse starting
if (chars[i] == ParseOpen) {
// Fault: end of string can't be the start of a parse
if (i + 1 >= chars.Length) {
throw new Exception($"No pair found for {ParseOpen}");
// Parse character was escaped
} else if (chars[i + 1] == ParseOpen) {
res.AddRange(GetCharInput(chars[i]));
i++;
// Parsing following text of parse area
} else {
var next = chars.IndexOfNext(ParseClose, i + 1);
// Fault: end of parse not found
if (next < 0)
throw new Exception($"No pair found for {ParseOpen}");
var length = next - (i + 1);
// Fault: parse string was empty
if (length < 1)
throw new Exception("A parse pair cannot be empty");
var temp = s.Substring(i + 1, length).ToLower();
// Parse string is a set of modifiers
if (Regex.IsMatch(temp, @"^[!+^#]{1,4}$")) {
foreach (var c in temp) pendingModifiers.Add(ShortModifiers[c]);
// Parse string is a set of stateful modifiers
} else if (Regex.IsMatch(temp, @"^[!+^#]{1,4} (down|up)$", RegexOptions.IgnoreCase)) {
Console.WriteLine("Parse stateful mods: " + temp);
var split = temp.Split(' ');
Console.WriteLine($"Split: {split[0]} : {split[1]}");
res.AddRange(split[0].Select(c => GetInput(ShortModifiers[c], split[1].ToLower() == "down")));
// Parse input has leading modifiers
} else if (pendingModifiers.Count > 0) {
res.AddRange(pendingModifiers.Select(k => GetInput(k, true)));
res.AddRange(new InputParseObject(temp).Parse());
res.AddRange(pendingModifiers.Select(k => GetInput(k, false)));
pendingModifiers.Clear();
// Parse string normally
} else {
res.AddRange(new InputParseObject(temp).Parse());
}
i = next;
}
// Parse close character outside of parse
} else if (chars[i] == ParseClose) {
if (i + 1 >= chars.Length)
throw new Exception($"Unexpected closing {ParseClose} at end of string");
if (chars[i + 1] != ParseClose)
throw new Exception($"Unexpected closing {ParseClose}");
res.AddRange(GetCharInput(ParseClose));
i++;
// Normal unicode characters
} else {
// Input character has leading modifiers
if (pendingModifiers.Count > 0) {
res.AddRange(pendingModifiers.Select(k => GetInput(k, true)));
res.AddRange(GetCharInput(chars[i]));
res.AddRange(pendingModifiers.Select(k => GetInput(k, false)));
pendingModifiers.Clear();
// Input character is handled normally
} else {
res.AddRange(GetCharInput(chars[i]));
}
}
}
return res.ToArray();
}
/// <summary>Return the index of the next matching item of an array</summary>
private static int IndexOfNext<T>(this T[] ar, T item, int start) {
for (int i = start; i < ar.Length; i++) {
if (ar[i].Equals(item)) {
return i;
}
}
return -1;
}
/// <summary>Object used to parse special text input</summary>
private class InputParseObject {
public bool Unicode { get; }
public bool? State { get; }
public int Count { get; }
public string KeyString { get; }
public Key? Key { get; }
public List<Key> Modifiers { get; private set; }
public List<WinAPI.INPUT> Inputs { get; private set; }
public InputParseObject(string s) {
if (!Regex.IsMatch(s, @"^[!+^#]*[^!+^#]+?( (text|down|up|\d+)){0,3}$", RegexOptions.IgnoreCase)) {
throw new Exception($"Unknown signature with '{s}'");
}
var data = s.Split(' ');
Unicode = false;
Count = 1;
for (int i = 1; i < data.Length; i++) {
var temp = data[i].ToLower();
if (temp == "text") {
Unicode = true;
} else if (temp == "down") {
if (State != null)
throw new Exception("Cannot have both 'down' and 'up' in the same command");
State = true;
} else if (temp == "up") {
if (State != null)
throw new Exception("Cannot have both 'down' and 'up' in the same command");
State = false;
} else {
Count = int.Parse(temp);
}
}
KeyString = Regex.Match(data[0], "(?<=^[!+^#]*)[^!+^#]*$").Value;
Key = Unicode ? null : (Key?)StringToKey(KeyString);
string modString = Regex.Match(data[0], "^[!+^#]").Value;
Modifiers = modString.Select(c => ShortModifiers[c]).ToList();
}
public List<WinAPI.INPUT> Parse() {
if (Inputs != null)
return Inputs;
Inputs = new List<WinAPI.INPUT>();
if (Modifiers.Count > 0) {
Inputs.AddRange(Modifiers.Select(m => GetInput(m, true)));
}
if (State != null) {
if (Unicode) {
Inputs.AddRange(KeyString.Select(c => GetCharInput(c)[(bool)State ? 0 : 1]));
} else {
Inputs.Add(GetKeyboardInput((Key)Key, (bool)State));
}
} else {
for (int i = 0; i < Count; i++) {
if (Unicode)
Inputs.AddRange(KeyString.SelectMany(c => GetCharInput(c)));
if (((Key)Key).IsStateless()) {
Inputs.Add(GetInput((Key)Key, true));
} else {
Inputs.Add(GetInput((Key)Key, true));
Inputs.Add(GetInput((Key)Key, false));
}
}
}
if (Modifiers.Count > 0) {
Inputs.AddRange(Modifiers.Select(m => GetInput(m, false)));
}
return Inputs;
}
}
#endregion
#endregion
}
}