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

yipeiwu_com5年前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字典多键值及重复键值的使用方法(详解)

python字典多键值及重复键值的使用方法(详解)

在Python中使用字典,格式如下: dict={ key1:value1 , key2;value2 ...} 在实际访问字典值时的使用格式如下: dict[key] 多...

Python中的集合类型知识讲解

Python中的集合类型知识讲解

集合类型         数学上,,把set称做由不同的元素组成的集合,集合(set)的成员通常被称做集合元素(se...

python获取外网IP并发邮件的实现方法

第一步:通过ip138来爬取外网ip 第二步:通过python的smtplib模块和email来发送邮件,具体用法去网上搜索, 下面是代码示例: #!/usr/bin/env pyt...

Flask实现图片的上传、下载及展示示例代码

Flask实现图片的上传、下载及展示示例代码

用Flask处理图片非常容易,这一篇学习一下图片的上传、下载及展示。还是以实例代码演示为主。 首先,实现一个简单的上传(过程中未做任何处理,只是为了演示) 点击选择图片,输入李四:...

python实现XML解析的方法解析

这篇文章主要介绍了python实现XML解析的方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 三种方法:一是xml.dom.*...