gpt4 book ai didi

python - 使用pyHook检测按键上下

转载 作者:行者123 更新时间:2023-11-30 22:38:48 26 4
gpt4 key购买 nike

我发现使用 pyHook 可以打印鼠标上下点击的脚本:

class record(object):
def OnMouseEvent(self, event):
print 'MessageName:',event.MessageName
print 'Message:',event.Message
print 'Time:',event.Time
print 'Window:',event.Window
print 'WindowName:',event.WindowName
print 'Position:',event.Position
print 'Wheel:',event.Wheel
print 'Injected:',event.Injected
print '---'
#time.sleep(1) #If I uncomment this, running the program will freeze stuff, as mentioned earlier.
return True

Record = record()
hm = pyHook.HookManager()
hm.MouseAll = Record.OnMouseEvent
hm.HookMouse()
pythoncom.PumpMessages()

当我使用 pyHook 以相同的方式检测键盘上的上下按键时,它仅显示按键按下

def OnKeyboardEvent(event): 
print ('MessageName:',event.MessageName )
print ('Message:',event.Message)
print ('Time:',event.Time)
print ('Window:',event.Window)
print ('WindowName:',event.WindowName)
print ('Ascii:', event.Ascii, chr(event.Ascii) )
print ('Key:', event.Key)
print ('KeyID:', event.KeyID)
print ('ScanCode:', event.ScanCode)
print ('Extended:', event.Extended)
print ('Injected:', event.Injected)
print ('Alt', event.Alt)
print ('Transition', event.Transition)
print ('---')
return True
# When the user presses a key down anywhere on their system
# the hook manager will call OnKeyboardEvent function.
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
try:
pythoncom.PumpMessages()
except KeyboardInterrupt:
pass

我怎样才能检测到按键按下?

最佳答案

这确实很晚了,但希望对某人有所帮助。您仅将 Hook 管理器注册为按键事件,因此这些是唯一显示的事件。您还需要订阅 KeyUp 事件。您可以将它们注册到相同的函数,如图所示,但请注意,对于一个项目,您可能希望将它们订阅到不同的方法。

def OnKeyboardEvent(event): 
print ('MessageName:',event.MessageName )
print ('Message:',event.Message)
print ('Time:',event.Time)
print ('Window:',event.Window)
print ('WindowName:',event.WindowName)
print ('Ascii:', event.Ascii, chr(event.Ascii) )
print ('Key:', event.Key)
print ('KeyID:', event.KeyID)
print ('ScanCode:', event.ScanCode)
print ('Extended:', event.Extended)
print ('Injected:', event.Injected)
print ('Alt', event.Alt)
print ('Transition', event.Transition)
print ('---')
return True

# When the user presses a key down anywhere on their system
# the hook manager will call OnKeyboardEvent function.
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
# Here we register the same function to the KeyUp event.
# Probably in practice you will create a different function to handle KeyUp functionality
hm.KeyUp = OnKeyboardEvent
hm.HookKeyboard()
try:
pythoncom.PumpMessages()
except KeyboardInterrupt:
pass

此外,根据您的 Python 版本,如果您在 OnKeyboardEvent 结束时未返回 True,则可能会遇到错误。您可能还想花一些时间阅读 HookManager.py。快乐的键盘记录!呃呃, children 注意安全

关于python - 使用pyHook检测按键上下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43417601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com