How to keep pynput and ctypes from clashing?

荒凉一梦 提交于 2019-12-04 22:36:43

I pip install input, and played a bit with it. My guessing was right, Pynput defines those structures, but with slightly different names, and sets argtypes (and restype) for ctypes.windll.user32.SendInput to its own definitions.
That's why when you try to supply instances of your structures, it sees it complains about type mismatch.

There are a number of solutions to fix this. Anyway, the simplest one was to simply replace your structs (you don't need them anymore) with the Pynput ones.

Note: It's just a dumb replace, things can be organized a lot nicer, and I'm sure that Pynput has a mechanism of its own to achieve this, in order to spare the user of writing this code.

The 2 modified versions of PressKey and ReleaseKey:

def PressKeyPynput(hexKeyCode):
    extra = ctypes.c_ulong(0)
    ii_ = pynput._util.win32.INPUT_union()
    ii_.ki = pynput._util.win32.KEYBDINPUT(0, hexKeyCode, 0x0008, 0, ctypes.cast(ctypes.pointer(extra), ctypes.c_void_p))
    x = pynput._util.win32.INPUT(ctypes.c_ulong(1), ii_)
    SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))

def ReleaseKeyPynput(hexKeyCode):
    extra = ctypes.c_ulong(0)
    ii_ = pynput._util.win32.INPUT_union()
    ii_.ki = pynput._util.win32.KEYBDINPUT(0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.cast(ctypes.pointer(extra), ctypes.c_void_p))
    x = pynput._util.win32.INPUT(ctypes.c_ulong(1), ii_)
    SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))

Note: A (more complex) variant encountered here: [SO]: ctypes.ArgumentError when using kivy with pywinauto.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!