Python数字虚拟按键不起作用

问题描述 投票:0回答:1

我正在尝试制作一个模拟按键的程序,这样我可以从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发送它。输入部分有效,但根本没有数字出现。

python ctypes virtual-keyboard
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.