我发现使用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


我如何也可以检测到按键?

最佳答案

这确实很晚,但希望对您有所帮助。您仅注册了挂钩管理器以按下事件,因此仅显示这些事件。您还需要订阅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。祝您键盘记录愉快!嗯,保持安全

07-24 15:41