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

yipeiwu_com6年前Python基础

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()。结果还算满意。

# -*- 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__":

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

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

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

相关文章

python and or用法详解

python and or用法详解

and 和 or 是python的两个逻辑运算符,可以使用and , or来进行多个条件内容的判断。下面通过代码简单说明下and or的用法: 1. or:当有一个条件为真时,该条件即为...

python语言元素知识点详解

指令和程序 计算机的硬件系统通常由五大部件构成,包括:运算器、控制器、存储器、输入设备和输出设备。其中,运算器和控制器放在一起就是我们通常所说的中央处理器,它的功能是执行各种运算和控制...

Python数据可视化 pyecharts实现各种统计图表过程详解

Python数据可视化 pyecharts实现各种统计图表过程详解

1、pyecharts介绍 Echarts是一款由百度公司开发的开源数据可视化JS库,pyecharts是一款使用python调用echarts生成数据可视化的类库,可实现柱状图,折...

利用Python绘制Jazz网络图的例子

利用Python绘制Jazz网络图的例子

最近在进行社交网络的学习,想利用Python来进行分析,但是网上关于这方面的资料好像很少,所以自己进行了一点研究,算是有一点点进步,现在将自己的成果发出来,希望这方面感兴趣的同学也可以快...

Python3 使用cookiejar管理cookie的方法

这次我们使用cookiejar来完成一个登录学校model平台,并查看登陆后的其他页面的任务 from urllib import request from urllib impor...