python - Python数字虚拟按键不起作用
问题描述
我正在尝试制作一个模拟按键的程序,以便我可以从 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 的答案。遗憾的是,我不再拥有该链接,但我知道它有效。
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)
推荐阅读
- java - 对象的数组列表只是创建对同一对象 java 的引用
- intellij-lombok-plugin - Lombok:setter 方法未被识别
- r - 使用 ggplot() 复制 plot()
- c++ - 使用 C++ 读取文件时,如何忽略一行
- java - CassandraIO 无法保存时间戳
- c# - 基于单元格文本的 Microsoft.Office.Interop.Excel.Cells 上的 C# 条件格式
- android - 如何为个人 android 项目获取 OpenStreetMaps 或 OpenTilesMaps API?
- json - 无法通过 Bot 向最终用户 (msteams) 发送消息
- python - 如何创建具有两个字段作为用户模型类型的表
- python-3.x - 如何在 Tensorflow-2.0 中绘制 tf.keras 模型?