创建ctypes阵列以使用sendinput发送扩展扫描码

2024-10-01 09:18:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想这样做:How to use extended scancodes in SendInput在Python中,使用ctypes

我可以使用Sendinput发送常规扫描码,但似乎无法发送Input数组,因此无法发送扩展扫描码。 到目前为止,我正在做的是。谁能给我指出正确的方向吗?这根本不起作用,我希望它按右CTRL键

import ctypes
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 InputI(ctypes.Union):
    _fields_ = [("ki", KeyBdInput),
                ("mi", MouseInput),
                ("hi", HardwareInput)]


class Input(ctypes.Structure):
    _fields_ = [("type", ctypes.c_ulong),
                ("ii", InputI)]


Inputx = Input * 2  # to create an array of Input, as mentionned in ctypes documentation


def press(scan_code):
    extra1 = ctypes.c_ulong(0)
    ii1_ = InputI()
    ii1_.ki = KeyBdInput(0, 0xE0, 0x0008, 0, ctypes.pointer(extra1))
    x1 = Input(ctypes.c_ulong(1), ii1_)
    extra2 = ctypes.c_ulong(0)
    ii_2 = InputI()
    ii_2.ki = KeyBdInput(1, scan_code, 0x0008, 0, ctypes.pointer(extra2))
    x2 = Input(ctypes.c_ulong(1), ii_2)
    x = Inputx(x1, x2)
    ctypes.windll.user32.SendInput(2, ctypes.pointer(x), ctypes.sizeof(x))

press(0x1D)


Tags: tofieldsinputctypesstructureclassiipointer
1条回答
网友
1楼 · 发布于 2024-10-01 09:18:40

我刚刚阅读了MSDN上的SendInput documentation并找到了解决方案:

右控件的扫描代码为0xE0 0x1D,因此要在KeyBdInput中使用的扫描代码必须为0x1D,若要指定它的前缀为0xE0,则flag参数的位#0必须设置为1,从而导致:

def press_ext(scan_code):
    extra = ctypes.c_ulong(0)
    ii_ = InputI()
    ii_.ki = KeyBdInput(0, scan_code, 0x0008 | 0x0001, 0, ctypes.pointer(extra))
    x = Input(ctypes.c_ulong(1), ii_)
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))


def release_ext(scan_code):
    extra = ctypes.c_ulong(0)
    ii_ = InputI()
    ii_.ki = KeyBdInput(0, scan_code, 0x0008 | 0x0002 | 0x0001, 0, ctypes.pointer(extra))
    x = Input(ctypes.c_ulong(1), ii_)
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))


press_ext(0x1D) # press RIGHT CTRL

release_ext(0x1D) #release it

相关问题 更多 >