当前位置:Gxlcms > Python > python中使用pyhook实现键盘监控的例子

python中使用pyhook实现键盘监控的例子

时间:2021-07-01 10:21:17 帮助过:77人阅读

pyhook下载:http://sourceforge.net/projects/pyhook/files/pyhook/1.5.1/

pyhookAPI手册:http://pyhook.sourceforge.net/doc_1.5.0/

以上网站上提供了几个使用的例子,另外安装pyhooks后,也会有一个例子的文件。于是拿来学习了一下,第一次运行时,提示没有pythoncom模块,就安装了pywin32,安装后,可以正常运行,但是会导致机器发卡,特别是中断程序运行后,鼠标会出现一段时间的自由晃动,找了半天原因,感觉主要是事件频率过高,程序会经常卡在pythoncom.PumpMessages()。

网上搜索了半天,看到有一帖子说是pythoncom.PumpMessages(n),n表示延迟时间,于是试着改了下,发现有一定效果,但不明显,后来想是不是因为没有终止程序,才会导致一直很卡呢,于是添加终止程序语句win32api.PostQuitMessage()。结果还算满意。

  1. # -*- coding: cp936 -*-
  2. import pythoncom
  3. import pyHook
  4. import time
  5. import win32api
  6. t=''
  7. asciistr=''
  8. keystr=''
  9. def onKeyboardEvent(event):
  10. global t,asciistr,keystr
  11. filename='d://test.txt'
  12. wrfile=open(filename,'ab')
  13. "处理键盘事件"
  14. if t==str(event.WindowName):
  15. asciistr=asciistr+chr(event.Ascii)
  16. keystr=keystr+str(event.Key)
  17. else:
  18. t=str(event.WindowName)
  19. if asciistr=='' and keystr=='':
  20. wrfile.writelines("\nWindow:%s\n" % str(event.Window))
  21. wrfile.writelines("WindowName:%s\n" % str(event.WindowName)) #写入当前窗体名
  22. wrfile.writelines("MessageName:%s\n" % str(event.MessageName))
  23. wrfile.writelines("Message:%d\n" % event.Message)
  24. wrfile.writelines("Time:%s\n" % time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
  25. else:
  26. wrfile.writelines("Ascii_char:%s\n" %asciistr)
  27. wrfile.writelines("Key_char:%s\n" %keystr)
  28. wrfile.writelines("\nWindow:%s\n" % str(event.Window))
  29. wrfile.writelines("WindowName:%s\n" % str(event.WindowName)) #写入当前窗体名
  30. wrfile.writelines("Time:%s\n" % time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
  31. asciistr=chr(event.Ascii)
  32. keystr=str(event.Key)
  33. if str(event.Key)=='F12': #按下F12后终止
  34. wrfile.writelines("Ascii_char:%s\n" %asciistr)
  35. wrfile.writelines("Key_char:%s\n" %keystr)
  36. wrfile.close()
  37. win32api.PostQuitMessage()
  38. return True
  39. if __name__ == "__main__":
  40. #创建hook句柄
  41. hm = pyHook.HookManager()
  42. #监控键盘
  43. hm.KeyDown = onKeyboardEvent
  44. hm.HookKeyboard()
  45. #循环获取消息
  46. pythoncom.PumpMessages(10000)

人气教程排行