本文实例讲述了Python实现监控键盘鼠标操作。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
# -*- 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程序设计有所帮助。
原文链接:https://blog.csdn.net/u011478909/article/details/50670430