好吧,我知道这个问题看似重复,但我不认为是这样。我已经阅读了关于涉及ctypes和SendKey的假按键的其他帖子。但是,我已经尝试了这些,但他们并没有按照我的意愿工作。我不想要一些类似于实际击键的东西,我想要一些与击键完全相同的东西。我已经用ctypes进行了一些测试,我注意到按键操作不像真正的键击一样。
例如,如果我打开记事本并按住A键,我会得到一个A字符,大约一秒后它会开始填充As。当我为A运行PressKey()时,它会键入一个A并且就是它。我仍然需要在A之后为A运行ReleaseKey(),这样其他程序就不会搞砸了。
我需要一些方法来执行类似realKeyPress(' A')的操作,并使其行为与我按下A键完全相同。另外,谢谢你们,你们总是那么快回答好的答案!
答案 0 :(得分:1)
所以我毕竟使用了ctypes。我在阅读了与此主题类似的其他答案后修改了ctypes代码。这是完成的代码:
import ctypes
import time
SendInput = ctypes.windll.user32.SendInput
# C struct redefinitions
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)]
# Actuals Functions
def PressKey(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 ReleaseKey(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))