-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdirectinput.py
More file actions
1593 lines (1332 loc) · 52.8 KB
/
directinput.py
File metadata and controls
1593 lines (1332 loc) · 52.8 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
"""
This module provides direct input control functions for simulating keyboard
and mouse events on Windows. It is useful for automated testing, creating
macros, and other applications requiring simulated user input.
"""
import ctypes
import mss
import pyscreeze
import pyperclip
import threading
import time
import os
from time import sleep
from collections import namedtuple
from contextlib import contextmanager
from ctypes import windll, wintypes, byref
from numpy import array
from cv2 import imread, cvtColor, COLOR_BGR2GRAY, COLOR_BGR2RGB
# Constants
DEFAULT_INTERVAL = 0.01
Point = namedtuple("Point", "x y")
Size = namedtuple("Size", "width height")
# KeyBdInput Flags
KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP = 0x0002
KEYEVENTF_SCANCODE = 0x0008
KEYEVENTF_UNICODE = 0x0004
# MapVirtualKey Map Types
MapVirtualKey = ctypes.windll.user32.MapVirtualKeyW
MAPVK_VK_TO_CHAR = 2
MAPVK_VK_TO_VSC = 0
MAPVK_VSC_TO_VK = 1
MAPVK_VSC_TO_VK_EX = 3
# Define direct key codes for SendInput()
DK_CODE = {
# Alphabets
'a': 0x1E, 'A': 0x1E,
'b': 0x30, 'B': 0x30,
'c': 0x2E, 'C': 0x2E,
'd': 0x20, 'D': 0x20,
'e': 0x12, 'E': 0x12,
'f': 0x21, 'F': 0x21,
'g': 0x22, 'G': 0x22,
'h': 0x23, 'H': 0x23,
'i': 0x17, 'I': 0x17,
'j': 0x24, 'J': 0x24,
'k': 0x25, 'K': 0x25,
'l': 0x26, 'L': 0x26,
'm': 0x32, 'M': 0x32,
'n': 0x31, 'N': 0x31,
'o': 0x18, 'O': 0x18,
'p': 0x19, 'P': 0x19,
'q': 0x10, 'Q': 0x10,
'r': 0x13, 'R': 0x13,
's': 0x1F, 'S': 0x1F,
't': 0x14, 'T': 0x14,
'u': 0x16, 'U': 0x16,
'v': 0x2F, 'V': 0x2F,
'w': 0x11, 'W': 0x11,
'x': 0x2D, 'X': 0x2D,
'y': 0x15, 'Y': 0x15,
'z': 0x2C, 'Z': 0x2C,
# Numbers
'num0': 0x52, '0': 0x0b, ')': 0x0b,
'num1': 0x4F, '1': 0x02, '!': 0x02,
'num2': 0x50, '2': 0x03, '@': 0x03,
'num3': 0x51, '3': 0x04, '#': 0x04,
'num4': 0x4B, '4': 0x05, '$': 0x05,
'num5': 0x4C, '5': 0x06, '%': 0x06,
'num6': 0x4D, '6': 0x07, '^': 0x07,
'num7': 0x47, '7': 0x08, '&': 0x08,
'num8': 0x48, '8': 0x09, '*': 0x09,
'num9': 0x49, '9': 0x0a, '(': 0x0a,
# Calculation keys
'num/': MapVirtualKey(0x6F, MAPVK_VK_TO_VSC),
'num.': 0x53,
'num-': 0x4A,
'num+': 0x4e,
'num*': 0x37,
# Arrow keys
'up': MapVirtualKey(0x26, MAPVK_VK_TO_VSC),
'left': MapVirtualKey(0x25, MAPVK_VK_TO_VSC),
'down': MapVirtualKey(0x28, MAPVK_VK_TO_VSC),
'right': MapVirtualKey(0x27, MAPVK_VK_TO_VSC),
# Control keys
'space': 0x39, ' ': 0x39,
'esc': 0x01,
'tab': 0x0F, '\t': 0x0F,
'backspace': 0x0E, '\b': 0x0E,
'enter': 0x1C, 'numenter': MapVirtualKey(0x0D, MAPVK_VK_TO_VSC), '\n': 0x1C, '\r': 0x1C,
'shift': 0x2A, 'lshift': 0x2A, 'rshift': 0x36,
'ctrl': 0x1D, 'lctrl': 0x1D, 'rctrl': MapVirtualKey(0x11, MAPVK_VK_TO_VSC),
'alt': 0x38, 'lalt': 0x38, 'ralt': MapVirtualKey(0x12, MAPVK_VK_TO_VSC),
'win': MapVirtualKey(0x5B, MAPVK_VK_TO_VSC), 'lwin': MapVirtualKey(0x5B, MAPVK_VK_TO_VSC), 'rwin': MapVirtualKey(0x5C, MAPVK_VK_TO_VSC),
'apps': 0xDD,
'capslock': 0x3A,
'numlock': 0x45,
'scrolllock': 0x46,
'insert': MapVirtualKey(0x2D, MAPVK_VK_TO_VSC),
'delete': MapVirtualKey(0x2E, MAPVK_VK_TO_VSC),
'home': MapVirtualKey(0x24, MAPVK_VK_TO_VSC),
'end': MapVirtualKey(0x23, MAPVK_VK_TO_VSC),
'pageup': MapVirtualKey(0x21, MAPVK_VK_TO_VSC),
'pagedown': MapVirtualKey(0x22, MAPVK_VK_TO_VSC),
'prtsc': MapVirtualKey(0x6A, MAPVK_VK_TO_VSC), 'sysrq': MapVirtualKey(0x6A, MAPVK_VK_TO_VSC),
# Function keys
'f1': 0x3B,
'f2': 0x3C,
'f3': 0x3D,
'f4': 0x3E,
'f5': 0x3F,
'f6': 0x40,
'f7': 0x41,
'f8': 0x42,
'f9': 0x43,
'f10': 0x44,
'f11': 0x57,
'f12': 0x58,
# Symbols
'`': 0x29, '~': 0x29,
'-': 0x0c, '_': 0x0c,
'=': 0x0d, '+': 0x0d,
'[': 0x1a, '{': 0x1a,
']': 0x1b, '}': 0x1b,
'\\': 0x2b, '|': 0x2b,
';': 0x27, ':': 0x27,
'\'': 0x28, '"': 0x28,
',': 0x33, '<': 0x33,
'.': 0x34, '>': 0x34,
'/': 0x35, '?': 0x35
}
# Define virtual key codes for GetAsyncKeyState()
VK_CODE = {
# Alphabets
'a': 0x41, 'A': 0x41,
'b': 0x42, 'B': 0x42,
'c': 0x43, 'C': 0x43,
'd': 0x44, 'D': 0x44,
'e': 0x45, 'E': 0x45,
'f': 0x46, 'F': 0x46,
'g': 0x47, 'G': 0x47,
'h': 0x48, 'H': 0x48,
'i': 0x49, 'I': 0x49,
'j': 0x4A, 'J': 0x4A,
'k': 0x4B, 'K': 0x4B,
'l': 0x4C, 'L': 0x4C,
'm': 0x4D, 'M': 0x4D,
'n': 0x4E, 'N': 0x4E,
'o': 0x4F, 'O': 0x4F,
'p': 0x50, 'P': 0x50,
'q': 0x51, 'Q': 0x51,
'r': 0x52, 'R': 0x52,
's': 0x53, 'S': 0x53,
't': 0x54, 'T': 0x54,
'u': 0x55, 'U': 0x55,
'v': 0x56, 'V': 0x56,
'w': 0x57, 'W': 0x57,
'x': 0x58, 'X': 0x58,
'y': 0x59, 'Y': 0x59,
'z': 0x5A, 'Z': 0x5A,
# Numbers
'num0': 0x60, '0': 0x30, ')': 0x30,
'num1': 0x61, '1': 0x31, '!': 0x31,
'num2': 0x62, '2': 0x32, '@': 0x32,
'num3': 0x63, '3': 0x33, '#': 0x33,
'num4': 0x64, '4': 0x34, '$': 0x34,
'num5': 0x65, '5': 0x35, '%': 0x35,
'num6': 0x66, '6': 0x36, '^': 0x36,
'num7': 0x67, '7': 0x37, '&': 0x37,
'num8': 0x68, '8': 0x38, '*': 0x38,
'num9': 0x69, '9': 0x39, '(': 0x39,
# Calculation keys
'num/': 0x6F,
'num.': 0x6E,
'num-': 0x6D,
'num+': 0x6B,
'num*': 0x6A,
# Arrow keys
'up': 0x26,
'down': 0x28,
'left': 0x25,
'right': 0x27,
# Control keys
'space': 0x20, ' ': 0x20,
'esc': 0x1B,
'tab': 0x09, '\t': 0x09,
'backspace': 0x08, '\b': 0x08,
'enter': 0x0D, 'numenter': 0x0D, '\n': 0x0D, '\r': 0x0D,
'shift': 0x10, 'lshift': 0x10, 'rshift': 0x10,
'ctrl': 0x11, 'lctrl': 0x11, 'rctrl': 0x11,
'alt': 0x12, 'lalt': 0x12, 'ralt': 0x12,
'win': 0x5B, 'lwin': 0x5B, 'rwin': 0x5C,
'apps': 0x5D,
'capslock': 0x14,
'numlock': 0x90,
'scrolllock': 0x91,
'insert': 0x2D,
'delete': 0x2E,
'home': 0x24,
'end': 0x23,
'pageup': 0x21,
'pagedown': 0x22,
'prtsc': 0x2C, 'sysrq': 0x2C,
# Function keys
'f1': 0x70,
'f2': 0x71,
'f3': 0x72,
'f4': 0x73,
'f5': 0x74,
'f6': 0x75,
'f7': 0x76,
'f8': 0x77,
'f9': 0x78,
'f10': 0x79,
'f11': 0x7A,
'f12': 0x7B,
# Symbols
'`': 0xC0, '~': 0xC0,
'-': 0xBD, '_': 0xBD,
'=': 0xBB, '+': 0xBB,
'[': 0xDB, '{': 0xDB,
']': 0xDD, '}': 0xDD,
'\\': 0xDC, '|': 0xDC,
';': 0xBA, ':': 0xBA,
'\'': 0xDE, '"': 0xDE,
',': 0xBC, '<': 0xBC,
'.': 0xBE, '>': 0xBE,
'/': 0xBF, '?': 0xBF
}
# Define keys that requires shift to be pressed
SHIFT_KEYS = [
')', '!', '@', '#', '$', '%', '^', '&', '*', '(', '~', '_',
'+', '{', '}', '|', ':', '"', '\n', '<', '>', '?',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z'
]
EXTENDED_KEYS = [
'up', 'down', 'left', 'right', 'numenter', 'num/',
'home', 'end', 'delete', 'insert', 'pageup', 'pagedown',
'prtsc', 'sysrq', 'ralt', 'rctrl', 'win', 'rwin', 'lwin'
]
# Define direct codes for mouse input (for SendInput)
MB_CODE = {
'left': 0x0002,
'right': 0x0008,
'middle': 0x0020
}
# Define virtual codes for mouse detection
MVB_CODE = {
'left_mouse': 0x01,
'right_mouse': 0x02,
'middle_mouse': 0x04,
'xbutton1': 0x05,
'xbutton2': 0x06
}
# Define mouse_event flags
MOUSEEVENTF_LEFTDOWN = 0x0002
MOUSEEVENTF_LEFTUP = 0x0004
MOUSEEVENTF_RIGHTDOWN = 0x0008
MOUSEEVENTF_RIGHTUP = 0x0010
MOUSEEVENTF_MIDDLEDOWN = 0x0020
MOUSEEVENTF_MIDDLEUP = 0x0040
MOUSEEVENTF_XDOWN = 0x0080
MOUSEEVENTF_XUP = 0x0100
# Define mouse data values for xbuttons (for mouse_event)
XBUTTON_DATA = {
'xbutton1': 0x0001,
'xbutton2': 0x0002
}
# C struct redefinitions
PUL = ctypes.POINTER(ctypes.c_ulong)
class KeyBdInput(ctypes.Structure):
_fields_ = [("wVk", ctypes.c_ushort),
("wScan", ctypes.c_ushort),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", PUL)]
class HardwareInput(ctypes.Structure):
_fields_ = [("uMsg", ctypes.c_ulong),
("wParamL", ctypes.c_short),
("wParamH", ctypes.c_ushort)]
class MouseInput(ctypes.Structure):
_fields_ = [("dx", ctypes.c_long),
("dy", ctypes.c_long),
("mouseData", ctypes.c_ulong),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", PUL)]
class Input_I(ctypes.Union):
_fields_ = [("ki", KeyBdInput),
("mi", MouseInput),
("hi", HardwareInput)]
class Input(ctypes.Structure):
_fields_ = [("type", ctypes.c_ulong),
("ii", Input_I)]
# Keyboard Functions
def keyDown(*keys):
"""
Simulate pressing down one or more keys.
Parameters:
*keys : str
One or more keys to press down. The key names should correspond to
the key mappings.
Example:
keyDown('x', 'y') or keyDown('a')
"""
# Get virtual key code
virtual_key_codes = []
for key in keys:
try:
hexKeyCode = DK_CODE[key.lower()]
except Exception:
hexKeyCode = 0x00
virtual_key_codes.append((key.lower(), hexKeyCode))
for key, hexKeyCode in virtual_key_codes:
keybdFlags = KEYEVENTF_SCANCODE
# Check if the character is in the shiftKeys list
if key in SHIFT_KEYS:
# Press the shift key
ctypes.windll.user32.keybd_event(0x10, 0, 0, 0)
# Check if the key is an arrow key and set the extended key flag
if key in EXTENDED_KEYS:
keybdFlags |= KEYEVENTF_EXTENDEDKEY
# Handle Num Lock state for arrow keys
if ctypes.windll.user32.GetKeyState(0x90):
# Send additional scancode if Num Lock is on
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, 0xE0, KEYEVENTF_SCANCODE, 0, ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
# Press the key
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, hexKeyCode, keybdFlags, 0, ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
# Check if the character is in the shiftKeys list
if key in SHIFT_KEYS:
# Release the shift key
ctypes.windll.user32.keybd_event(0x10, 0, 2, 0)
def keyUp(*keys):
"""
Simulate releasing one or more keys.
Parameters:
*keys : str
One or more keys to release. The key names should correspond to
the key mappings.
Example:
keyUp('x', 'y') or keyUp('a')
"""
# Get virtual key code
virtual_key_codes = []
for key in keys:
try:
hexKeyCode = DK_CODE[key.lower()]
except Exception:
hexKeyCode = 0x00
virtual_key_codes.append((key.lower(), hexKeyCode))
for key, hexKeyCode in virtual_key_codes:
keybdFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP
# Check if the character is in the shiftKeys list
if key in SHIFT_KEYS:
# Press the shift key
ctypes.windll.user32.keybd_event(0x10, 0, 0, 0)
# Check if the key is an arrow key and set the extended key flag
if key in EXTENDED_KEYS:
keybdFlags |= KEYEVENTF_EXTENDEDKEY
# Handle Num Lock state for arrow keys
if ctypes.windll.user32.GetKeyState(0x90):
# Send additional scancode if Num Lock is on
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, 0xE0, KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP, 0,
ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
# Release the key
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, hexKeyCode, keybdFlags, 0, ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
# Check if the character is in the shiftKeys list
if key in SHIFT_KEYS:
# Release the shift key
ctypes.windll.user32.keybd_event(0x10, 0, 2, 0)
@contextmanager
def keyHold(*keys):
"""
Simulate holding down one or more specified keys.
This function simulates pressing and holding one or more specified keys.
The keys parameter should be a string, not a list. This function should be
used with a `with` statement to ensure that the keys are released after the
block of code is executed.
Parameters:
*keys : str
One or more keys to hold down. The key names should correspond to
the key mappings.
Example:
with keyHold('ctrl', 'shift'):
keyPress('esc')
"""
# Get the virtual key codes
virtual_key_codes = []
for key in keys:
try:
hexKeyCode = DK_CODE[key.lower()]
except Exception:
hexKeyCode = 0x00
virtual_key_codes.append((key.lower(), hexKeyCode))
for key, hexKeyCode in virtual_key_codes:
keybdFlags = KEYEVENTF_SCANCODE
# Check if the key is an arrow key and set the extended key flag
if key in EXTENDED_KEYS:
keybdFlags |= KEYEVENTF_EXTENDEDKEY
# Handle Num Lock state for arrow keys
if ctypes.windll.user32.GetKeyState(0x90):
# Send additional scancode if Num Lock is on
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, 0xE0, KEYEVENTF_SCANCODE, 0, ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
# Press the key
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, hexKeyCode, keybdFlags, 0, ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
# Yield control to the calling function
yield
for key, hexKeyCode in virtual_key_codes:
keybdFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP
# Check if the key is an arrow key and set the extended key flag
if key in EXTENDED_KEYS:
keybdFlags |= KEYEVENTF_EXTENDEDKEY
# Handle Num Lock state for arrow keys
if ctypes.windll.user32.GetKeyState(0x90):
# Send additional scancode if Num Lock is on
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, 0xE0, KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP, 0,
ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
# Release the key
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, hexKeyCode, keybdFlags, 0, ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
def keyPress(keys, interval=0, presses=1,
key_delay=DEFAULT_INTERVAL, simultaneously=False):
"""
Simulate pressing one or more keys.
This function simulates pressing and releasing one or more specified keys.
The keys parameter can be a single key or a list of keys. The keys can be
pressed either simultaneously or sequentially based on the
`simultaneously` parameter. Additionally, the function allows specifying
the number of times to press the keys and the interval between presses.
Parameters:
keys : str or list of str
The key or list of keys to press. The key names should correspond to
the key mappings.
interval : float, optional
The interval between key presses in seconds (default is 0.01).
presses : int, optional
The number of times to press the keys (default is 1).
key_delay : float, optional
The delay between each key press and release in seconds (default is 0.01).
simultaneously : bool, optional
Whether to press all keys at once (default is False).
If False, keys are pressed sequentially.
Example:
keyPress('a') # Press the 'a' key once.
keyPress(['ctrl', 'c']) # Press 'ctrl' and 'c' sequentially.
keyPress(['ctrl', 'shift'], simultaneously=True) # Press 'ctrl' and 'shift' simultaneously.
keyPress('b', presses=3, interval=0.5) # Press the 'b' key 3 times with 0.5-second interval.
"""
if not isinstance(keys, list):
keys = [keys]
if simultaneously:
for _ in range(presses):
press_inputs = []
release_inputs = []
for key in keys:
# Get virtual key code
try:
hexKeyCode = DK_CODE[key.lower()]
except Exception:
hexKeyCode = 0x00
keybdFlags = KEYEVENTF_SCANCODE
# Check if the character is in the shiftKeys list
if key in SHIFT_KEYS:
# Press the shift key
ctypes.windll.user32.keybd_event(0x10, 0, 0, 0)
# Check if the key is an arrow key and set the extended key flag
if key in EXTENDED_KEYS:
keybdFlags |= KEYEVENTF_EXTENDEDKEY
# Handle Num Lock state for arrow keys
if ctypes.windll.user32.GetKeyState(0x90):
# Send additional scancode if Num Lock is on
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, 0xE0, KEYEVENTF_SCANCODE, 0, ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
# Press
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, hexKeyCode, keybdFlags, 0, ctypes.pointer(extra)
)
press_inputs.append(Input(ctypes.c_ulong(1), ii_))
# Release
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, hexKeyCode, keybdFlags | KEYEVENTF_KEYUP, 0,
ctypes.pointer(extra)
)
release_inputs.append(Input(ctypes.c_ulong(1), ii_))
# Check if the character is in the shiftKeys list
if key in SHIFT_KEYS:
# Release the shift key
ctypes.windll.user32.keybd_event(0x10, 0, 2, 0)
press_inputs_array = (Input * len(keys))()
for i, input_obj in enumerate(press_inputs):
press_inputs_array[i] = input_obj
ctypes.windll.user32.SendInput(
len(keys), ctypes.pointer(press_inputs_array),
ctypes.sizeof(Input)
)
sleep(key_delay)
release_inputs_array = (Input * len(keys))()
for i, input_obj in enumerate(release_inputs):
release_inputs_array[i] = input_obj
ctypes.windll.user32.SendInput(
len(keys), ctypes.pointer(release_inputs_array),
ctypes.sizeof(Input)
)
sleep(interval)
else:
for _ in range(presses):
for key in keys:
# Get virtual key code
try:
hexKeyCode = DK_CODE[key.lower()]
except Exception:
hexKeyCode = 0x00
keybdFlags = KEYEVENTF_SCANCODE
# Check if the character is in the shiftKeys list
if key in SHIFT_KEYS:
# Press the shift key
ctypes.windll.user32.keybd_event(0x10, 0, 0, 0)
# Check if the key is an arrow key and set the extended key flag
if key in EXTENDED_KEYS:
keybdFlags |= KEYEVENTF_EXTENDEDKEY
# Handle Num Lock state for arrow keys
if ctypes.windll.user32.GetKeyState(0x90):
# Send additional scancode if Num Lock is on
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, 0xE0, KEYEVENTF_SCANCODE, 0, ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
# Press
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, hexKeyCode, keybdFlags, 0, ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
sleep(key_delay)
# Release
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, hexKeyCode, keybdFlags | KEYEVENTF_KEYUP, 0, ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
# Check if the character is in the shiftKeys list
if key in SHIFT_KEYS:
# Release the shift key
ctypes.windll.user32.keybd_event(0x10, 0, 2, 0)
sleep(interval)
def hotKey(*keys, **kwargs):
"""
Simulate pressing a combination of keys simultaneously.
This function simulates pressing and holding down a combination of keys simultaneously,
followed by releasing them.
The keys parameter can accept multiple key arguments to form the hotkey combination.
Parameters:
*keys : str
One or more keys to press as part of the hotkey combination.
The key names should correspond to
the key mappings.
key_delay : float, optional
The delay between each key press and release in seconds (default is 0.01).
Example:
hotKey('ctrl', 'shift', 'esc') # Simulate pressing 'Ctrl + Shift + Esc' simultaneously.
"""
key_delay = kwargs.get('key_delay', DEFAULT_INTERVAL)
# Get the virtual key codes for the keys in the hotkey sequence
virtual_key_codes = []
for key in keys:
# Get virtual key code
try:
hexKeyCode = DK_CODE[key.lower()]
except Exception:
hexKeyCode = 0x00
virtual_key_codes.append((key.lower(), hexKeyCode))
# Press the keys in the hotkey sequence
for key, hexKeyCode in virtual_key_codes:
keybdFlags = KEYEVENTF_SCANCODE
# Check if the key is an arrow key and set the extended key flag
if key in EXTENDED_KEYS:
keybdFlags |= KEYEVENTF_EXTENDEDKEY
# Handle Num Lock state for arrow keys
if ctypes.windll.user32.GetKeyState(0x90):
# Send additional scancode if Num Lock is on
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, 0xE0, KEYEVENTF_SCANCODE, 0, ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
# Press
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, hexKeyCode, keybdFlags, 0, ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
sleep(key_delay)
# Release the keys in reverse order
for key, hexKeyCode in reversed(virtual_key_codes):
keybdFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP
# Check if the key is an arrow key and set the extended key flag
if key in EXTENDED_KEYS:
keybdFlags |= KEYEVENTF_EXTENDEDKEY
# Handle Num Lock state for arrow keys
if ctypes.windll.user32.GetKeyState(0x90):
# Send additional scancode if Num Lock is on
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, 0xE0, KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP, 0,
ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
# Release
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(
0, hexKeyCode, keybdFlags, 0, ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
sleep(key_delay)
def write(text: str, interval=0.0, key_delay=0.001):
"""
Types out a given text string.
This function simulates typing out a given text string character by character.
Optionally, a speed (in seconds) between key presses can be specified to
simulate a more natural typing speed. If a character is not recognized,
it will be copied and pasted from the clipboard.
Parameters:
text : str
The text string to type out.
interval : float, optional
The interval (in seconds) between each character (default is 0.0).
key_delay : float, optional
The delay between key press and release for each character (default is 0.03 seconds).
Example:
write("Hello, World!", interval=0.1)
"""
# Load the user32 library
user32 = ctypes.windll.user32
# Iterate through each character in the text
for c in text:
# Look up the virtual key code for the character
# in the VK_CODE dictionary
try:
vk_code = VK_CODE[c]
except Exception:
# If the character isn't in the VK_CODE,
# copy it to the clipboard and simulate a paste operation
pyperclip.copy(c)
hotKey('ctrl', 'v', interval=key_delay)
else:
# Check if the character is in the shiftKeys list
if c in SHIFT_KEYS:
# Press the shift key
user32.keybd_event(0x10, 0, 0, 0)
# Send a WM_KEYDOWN message for the key
# corresponding to the virtual key code
user32.keybd_event(vk_code, 0, 0, 0)
sleep(key_delay)
# Send a WM_KEYUP message for the key
# corresponding to the virtual key code
user32.keybd_event(vk_code, 0, 2, 0)
# Check if the character is in the shiftKeys list
if c in SHIFT_KEYS:
# Release the shift key
user32.keybd_event(0x10, 0, 2, 0)
# Define the time delay between each characters
sleep(interval)
def keyDetect(*keys):
"""
Check if one or more specified keys are currently pressed.
This function checks the state of one or more specified keys to determine
if they are currently pressed. The keys parameter can be a single key (as a string) or a combination.
The function returns True if all specified keys are pressed,
and False if any key is not pressed or not recognized.
Parameters:
keys : str
The key or list of keys to check. The key names should correspond to
the key mappings.
It can take keyboard keys and also mouse buttons.
Returns:
bool
True if all specified keys are pressed, False otherwise.
Example:
keyDetect('a') # Check if the 'a' key is pressed.
keyDetect('ctrl', 'c') # Check if both 'ctrl' and 'c' keys are pressed.
keyDetect('left_mouse') # Check if left mouse button is pressed.
keyDetect('xbutton1') # Check if mouse xbutton1 is pressed.
"""
user32 = ctypes.windll.user32
KEY_CODE = {**VK_CODE, **MVB_CODE}
# Check if keys is a single key (string) and convert it to a list
if isinstance(keys, str):
keys = [keys]
pressed_keys = []
for key_code in range(0x01, 0xFE):
key_state = user32.GetAsyncKeyState(key_code)
if key_state & 0x8000: # Check if key is held down
pressed_keys.append(hex(key_code))
for key in keys:
if hex(KEY_CODE.get(key.lower(), 0)) not in pressed_keys:
return False
# If all keys are pressed, return True
return True
# Mouse Functions
def mouseClick(button='left', interval=0, presses=1,
key_delay=DEFAULT_INTERVAL):
"""
Simulate mouse click events.
This function simulates mouse click events for a specified mouse button.
The button parameter determines which mouse button to click,
and the presses parameter specifies the number of times to click the button.
Parameters:
button : str, optional
The mouse button to click ('left', 'right', 'middle', 'xbutton1', or 'xbutton2'). Default is 'left'.
interval : float, optional
The interval (in seconds) between each clicks.
presses : int, optional
The number of times to click the mouse button. Default is 1.
key_delay: float, optional
The delay (in seconds) between each click down and click release.
Example:
mouseClick('left') # Click the left mouse button once.
mouseClick('right', presses=2, interval=0.5) # Double-click the right mouse button with a 0.5-second interval.
mouseClick('middle', presses=3) # Triple-click the middle mouse button.
mouseClick('xbutton1') # Click the first extra mouse button (xbutton1).
mouseClick('xbutton2') # Click the second extra mouse button (xbutton2).
"""
button = button.lower()
# Use different approach for xbuttons vs regular buttons
if button in ['xbutton1', 'xbutton2']:
# Get the xbutton data value
mouse_data = XBUTTON_DATA.get(button, 0)
for _ in range(presses):
# Press the xbutton
ctypes.windll.user32.mouse_event(MOUSEEVENTF_XDOWN, 0, 0, mouse_data, 0)
sleep(key_delay)
# Release the xbutton
ctypes.windll.user32.mouse_event(MOUSEEVENTF_XUP, 0, 0, mouse_data, 0)
sleep(interval)
else:
# Regular buttons use SendInput
button_code = MB_CODE.get(button)
for _ in range(presses):
# Send mouse button press event
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.mi = MouseInput(0, 0, 0, button_code, 0, ctypes.pointer(extra))
x = Input(ctypes.c_ulong(0), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
sleep(key_delay)
# Send mouse button release event
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.mi = MouseInput(
0, 0, 0, button_code << 1, 0, ctypes.pointer(extra)
)
x = Input(ctypes.c_ulong(0), ii_)
ctypes.windll.user32.SendInput(
1, ctypes.pointer(x), ctypes.sizeof(x)
)
sleep(interval)