2017-04-14 64 views
1

我发现脚本,通过使用pyHook可以打印点击鼠标上下:使用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 

我怎样才能检测到关键?

回答

1

这真的很晚,但希望它有助于某人。您只注册挂钩管理器来关闭事件,所以这些是唯一显示的事件。您还需要订阅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。快乐的键盘记录!呃,保持安全的孩子