Python数字虚拟按键不起作用

时间:2019-03-09 20:18:17

标签: python ctypes virtual-keyboard

我正在尝试制作一个模拟按键的程序,以便可以从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)

这是指逐个字符地键入数字,然后按Enter键发送。输入部分有效,但完全没有数字出现。

1 个答案:

答案 0 :(得分:0)

尝试使用此代码发送输入。我从另一个问题中得出的结论几乎是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)