Python数字虚拟按键不起作用
Posted
技术标签:
【中文标题】Python数字虚拟按键不起作用【英文标题】:Python numerical virtual key press doesn't work 【发布时间】:2019-03-09 20:18:16 【问题描述】:我正在尝试制作一个模拟按键的程序,以便我可以从 X 数到 Y。
到目前为止,这是我的代码:
import ctypes,time
user32 = ctypes.windll.user32
def word_to_keybdinput(word):
for letter in word:
if letter in ("0","1","2","3","4","5","6","7","8","9"):
hex_str = hex(ord(letter)-18)
hex_int = int(hex_str,0)
#two lines above change number
#into hex for virtual key code
user32.keybd_event(hex_int,0,2,0) #2 is the code for KEYDOWN
user32.keybd_event(hex_int,0,0,0) #0 is the code for KEYUP
time.sleep(2)
start = 1
end = 10000
for i in range(start,end):
word_to_keybdinput(str(i))
user32.keybd_event(0x0D,0,2,0)
user32.keybd_event(0x0D,0,0,0)
time.sleep(2.3)
这意味着一个字符一个字符地输入数字,然后按回车键发送它。输入部分有效,但根本没有出现数字。
【问题讨论】:
【参考方案1】:试试这个代码来发送输入。我从另一个问题中得到了几乎 1:1 的答案。很遗憾,我不再拥有该链接,但我知道它有效。
import ctypes, time
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)]
def KeyDown(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra))
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def KeyRelease(hexKeyCode):
extra = ctypes.c_ulong(0)
ii_ = Input_I()
ii_.ki = KeyBdInput(0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra))
x = Input(ctypes.c_ulong(1), ii_)
ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
def PressKey(hexKeyCode):
"""
Send a keypress using scancodes
http://www.gamespp.com/directx/directInputKeyboardScanCodes.html
"""
KeyDown(hexKeyCode)
time.sleep(0.05)
KeyRelease(hexKeyCode)
例子:
time.sleep(1)
PressKey(0x1C)
PressKey(0x02)
【讨论】:
以上是关于Python数字虚拟按键不起作用的主要内容,如果未能解决你的问题,请参考以下文章
PySide2 QOpenGLWidget 按键事件不起作用