加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-17 07:23:25 所属栏目:Python 来源:网络整理
导读:pyhook下载:http://sourceforge.net/projects/pyhook/files/pyhook/1.5.1/ pyhookAPI手册:http://pyhook.sourceforge.net/doc_1.5.0/ 以上网站上提供了几个使用的例子,另外安装pyhooks后,也会有一个例子的文件。于是拿来学习了一下,第一次运行时,提示

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:%sn" % str(event.Window))
      wrfile.writelines("WindowName:%sn" % str(event.WindowName)) #写入当前窗体名
      wrfile.writelines("MessageName:%sn" % str(event.MessageName))
      wrfile.writelines("Message:%dn" % event.Message)
      wrfile.writelines("Time:%sn" % time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
    else:
      wrfile.writelines("Ascii_char:%sn" %asciistr)
      wrfile.writelines("Key_char:%sn" %keystr)
      wrfile.writelines("nWindow:%sn" % str(event.Window))
      wrfile.writelines("WindowName:%sn" % str(event.WindowName)) #写入当前窗体名
      wrfile.writelines("Time:%sn" % 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:%sn" %asciistr)
    wrfile.writelines("Key_char:%sn" %keystr)
    wrfile.close()  
    win32api.PostQuitMessage()
    
  return True
  
  

if __name__ == "__main__":

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

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

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

您可能感兴趣的文章:

  • Python中使用PyHook监听鼠标和键盘事件实例
  • Python利用pyHook实现监听用户鼠标与键盘事件
  • python基于windows平台锁定键盘输入的方法
  • Python读取键盘输入的2种方法
  • Python中的模块导入和读取键盘输入的方法
  • 玩转python selenium鼠标键盘操作(ActionChains)
  • 利用Python实现Windows下的鼠标键盘模拟的实例代码
  • python方向键控制上下左右代码

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读