forked from tanjeffreyz/auto-maple
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vkeys.py
225 lines (184 loc) · 6.1 KB
/
vkeys.py
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
"""A module for simulating low-level keyboard and mouse key presses."""
import ctypes
import time
import utils
import win32con
import win32api
from ctypes import wintypes
from random import random
user32 = ctypes.WinDLL('user32', use_last_error=True)
INPUT_MOUSE = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2
KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP = 0x0002
KEYEVENTF_UNICODE = 0x0004
KEYEVENTF_SCANCODE = 0x0008
MAPVK_VK_TO_VSC = 0
# https://docs.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes?redirectedfrom=MSDN
key_map = {'tab': 0x09, # Special Keys
'alt': 0x12,
'space': 0x20,
'lshift': 0xA0,
'ctrl': 0x11,
'del': 0x2E,
'end': 0x23,
'pgup': 0x21,
'pgdown': 0x22,
'left': 0x25, # Arrow keys
'up': 0x26,
'right': 0x27,
'down': 0x28,
'0': 0x30, # Numbers
'1': 0x31,
'2': 0x32,
'3': 0x33,
'4': 0x34,
'5': 0x35,
'6': 0x36,
'7': 0x37,
'8': 0x38,
'9': 0x39,
'f1': 0x70, # Function keys
'f2': 0x71,
'f3': 0x72,
'f4': 0x73,
'f5': 0x74,
'f6': 0x75,
'f7': 0x76,
'f8': 0x77,
'f9': 0x78,
'f10': 0x79,
'f11': 0x7A,
'f12': 0x7B,
'a': 0x41, # Letters
'b': 0x42,
'c': 0x43,
'd': 0x44,
'e': 0x45,
'f': 0x46,
'g': 0x47,
'h': 0x48,
'i': 0x49,
'j': 0x4A,
'k': 0x4B,
'l': 0x4C,
'm': 0x4D,
'n': 0x4E,
'o': 0x4F,
'p': 0x50,
'q': 0x51,
'r': 0x52,
's': 0x53,
't': 0x54,
'u': 0x55,
'v': 0x56,
'w': 0x57,
'x': 0x58,
'y': 0x59,
'z': 0x5A}
#################################
# C Struct Definitions #
#################################
wintypes.ULONG_PTR = wintypes.WPARAM
class KeyboardInput(ctypes.Structure):
_fields_ = (('wVk', wintypes.WORD),
('wScan', wintypes.WORD),
('dwFlags', wintypes.DWORD),
('time', wintypes.DWORD),
('dwExtraInfo', wintypes.ULONG_PTR))
def __init__(self, *args, **kwargs):
super(KeyboardInput, self).__init__(*args, **kwargs)
if not self.dwFlags & KEYEVENTF_UNICODE:
self.wScan = user32.MapVirtualKeyExW(self.wVk, MAPVK_VK_TO_VSC, 0)
class MouseInput(ctypes.Structure):
_fields_ = (('dx', wintypes.LONG),
('dy', wintypes.LONG),
('mouseData', wintypes.DWORD),
('dwFlags', wintypes.DWORD),
('time', wintypes.DWORD),
('dwExtraInfo', wintypes.ULONG_PTR))
class HardwareInput(ctypes.Structure):
_fields_ = (('uMsg', wintypes.DWORD),
('wParamL', wintypes.WORD),
('wParamH', wintypes.WORD))
class Input(ctypes.Structure):
class _Input(ctypes.Union):
_fields_ = (('ki', KeyboardInput),
('mi', MouseInput),
('hi', HardwareInput))
_anonymous_ = ('_input',)
_fields_ = (('type', wintypes.DWORD),
('_input', _Input))
LPINPUT = ctypes.POINTER(Input)
def err_check(result, _, args):
if result == 0:
raise ctypes.WinError(ctypes.get_last_error())
else:
return args
user32.SendInput.errcheck = err_check
user32.SendInput.argtypes = (wintypes.UINT, LPINPUT, ctypes.c_int)
#################################
# Functions #
#################################
@utils.run_if_enabled
def key_down(key):
"""
Simulates a key-down action. Can be cancelled by Bot.toggle_enabled.
:param key: The key to press.
:return: None
"""
key = key.lower()
if key not in key_map.keys():
print(f"Invalid keyboard input: '{key}'.")
else:
x = Input(type=INPUT_KEYBOARD, ki=KeyboardInput(wVk=key_map[key]))
user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))
def key_up(key):
"""
Simulates a key-up action. Cannot be cancelled by Bot.toggle_enabled.
This is to ensure no keys are left in the 'down' state when the program pauses.
:param key: The key to press.
:return: None
"""
key = key.lower()
if key not in key_map.keys():
print(f"Invalid keyboard input: '{key}'.")
else:
x = Input(type=INPUT_KEYBOARD, ki=KeyboardInput(wVk=key_map[key], dwFlags=KEYEVENTF_KEYUP))
user32.SendInput(1, ctypes.byref(x), ctypes.sizeof(x))
@utils.run_if_enabled
def press(key, n, down_time=0.05, up_time=0.1):
"""
Presses KEY N times, holding it for DOWN_TIME seconds, and releasing for UP_TIME seconds.
:param key: The keyboard input to press.
:param n: Number of times to press KEY.
:param down_time: Duration of down-press (in seconds).
:param up_time: Duration of release (in seconds).
:return: None
"""
for _ in range(n):
key_down(key)
time.sleep(down_time * (0.8 + 0.4 * random()))
key_up(key)
time.sleep(up_time * (0.8 + 0.4 * random()))
@utils.run_if_enabled
def click(position, button='left'):
"""
Simulate a mouse click with BUTTON at POSITION.
:param position: The (x, y) position at which to click.
:param button: Either the left or right mouse button.
:return: None
"""
if button not in ['left', 'right']:
print(f"'{button}' is not a valid mouse button.")
else:
if button == 'left':
down_event = win32con.MOUSEEVENTF_LEFTDOWN
up_event = win32con.MOUSEEVENTF_LEFTUP
else:
down_event = win32con.MOUSEEVENTF_RIGHTDOWN
up_event = win32con.MOUSEEVENTF_RIGHTUP
win32api.SetCursorPos(position)
win32api.mouse_event(down_event, position[0], position[1], 0, 0)
win32api.mouse_event(up_event, position[0], position[1], 0, 0)