Python实现监控键盘鼠标操作示例【基于pyHook与pythoncom模块】

yipeiwu_com7年前Python基础

本文实例讲述了Python实现监控键盘鼠标操作。分享给大家供大家参考,具体如下:

# -*- coding: utf-8 -*-
import pythoncom
import pyHook
import time
def onMouseEvent(event):
  "处理鼠标事件"
  fobj.writelines('-' * 20 + 'MouseEvent Begin' + '-' * 20 + '\n')
  fobj.writelines("Current Time:%s\n" % time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime()))
  fobj.writelines("MessageName:%s\n" % str(event.MessageName))
  fobj.writelines("Message:%d\n" % event.Message)
  fobj.writelines("Time_sec:%d\n" % event.Time)
  fobj.writelines("Window:%s\n" % str(event.Window))
  fobj.writelines("WindowName:%s\n" % str(event.WindowName))
  fobj.writelines("Position:%s\n" % str(event.Position))
  fobj.writelines('-' * 20 + 'MouseEvent End' + '-' * 20 + '\n')
  return True
def onKeyboardEvent(event):
  "处理键盘事件"
  fobj.writelines('-' * 20 + 'Keyboard Begin' + '-' * 20 + '\n')
  fobj.writelines("Current Time:%s\n" % time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime()))
  fobj.writelines("MessageName:%s\n" % str(event.MessageName))
  fobj.writelines("Message:%d\n" % event.Message)
  fobj.writelines("Time:%d\n" % event.Time)
  fobj.writelines("Window:%s\n" % str(event.Window))
  fobj.writelines("WindowName:%s\n" % str(event.WindowName))
  fobj.writelines("Ascii_code: %d\n" % event.Ascii)
  fobj.writelines("Ascii_char:%s\n" % chr(event.Ascii))
  fobj.writelines("Key:%s\n" % str(event.Key))
  fobj.writelines('-' * 20 + 'Keyboard End' + '-' * 20 + '\n')
  return True
#打开日志文件
file_name = "E:\\hook_log.txt"
fobj = open(file_name, 'w')
#创建hook句柄
hm = pyHook.HookManager()
#监控键盘
hm.KeyDown = onKeyboardEvent
hm.HookKeyboard()
#监控鼠标
hm.MouseAll = onMouseEvent
hm.HookMouse()
#循环获取消息
pythoncom.PumpMessages()
#关闭日志文件
fobj.close()

运行后可在E盘根目录下创建一个hook_log.txt文件,用于记录监控键盘、鼠标操作信息。如下图所示:

注:代码中所用到的pythoncom与pyHook模块可点击此处下载响应版本的whl文件再进入whl文件目录使用pip install命令进行安装

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

相关文章

python计算两个地址之间的距离方法

我们调用高德地图的API来计算经纬度 #计算地址经纬度 import requests def geocode(address): parameters = {'address':...

Numpy中的mask的使用

Numpy中的mask的使用

numpy中矩阵选取子集或者以条件选取子集,用mask是一种很好的方法 简单来说就是用bool类型的indice矩阵去选择, mask = np.ones(X.shape[0],...

对python中字典keys,values,items的使用详解

在python中对字典进行遍历时,可以直接使用如下模式: dict = {"name": "jack", "age": 15, "height": 1.75} for k...

python 接收处理外带的参数方法

在执行python 代码的时候,有时候需要传递外面的参数进行处理 这个该怎么实现呢? 需要一个模块 from sys import argv 当然也可以直接只导入 sys im...

python通过文件头判断文件类型

对于提供上传的服务器,需要对上传的文件进行过滤。 本文为大家提供了python通过文件头判断文件类型的方法,避免不必要的麻烦。 分享代码如下 import struct # 支...