我是靠谱客的博主 悦耳衬衫,这篇文章主要介绍PyHook3实现监控键盘鼠标操作1. 创建HookManager对象,现在分享给大家,希望可以做个参考。

1. 创建HookManager对象

复制代码
1
2
import PyHook3 hm = PyHook3.HookManager()

之后的操作都是基于这个Manager对象进行。

2. 编写事件处理函数
事件处理函数需要传入一个HookEvent对象,这个类有两个子类,一个为鼠标事件MouseEvent,还有一个为键盘事件KeyboardEvent,分别为当触发相应事件时由系统传入。
MouseEvent及KeyboardEvent又分别有多个属性,代表所触发事件的具体信息。example.py已经列出了所有属性,通过对example.py例子的注释,大概就能清楚了:

复制代码
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
# 鼠标事件处理函数 def OnMouseEvent(event):   print('MessageName:',event.MessageName)  #事件名称   print('Message:',event.Message)          #windows消息常量    print('Time:',event.Time)                #事件发生的时间戳           print('Window:',event.Window)            #窗口句柄            print('WindowName:',event.WindowName)    #窗口标题   print('Position:',event.Position)        #事件发生时相对于整个屏幕的坐标   print('Wheel:',event.Wheel)              #鼠标滚轮   print('Injected:',event.Injected)        #判断这个事件是否由程序方式生成,而不是正常的人为触发。   print('---')   # 返回True代表将事件继续传给其他句柄,为False则停止传递,即被拦截   return True #键盘事件处理函数 def OnKeyboardEvent(event):   print('MessageName:',event.MessageName)          #同上,共同属性不再赘述   print('Message:',event.Message)   print('Time:',event.Time)   print('Window:',event.Window)   print('WindowName:',event.WindowName)   print('Ascii:', event.Ascii, chr(event.Ascii))   #按键的ASCII码   print('Key:', event.Key)                         #按键的名称   print('KeyID:', event.KeyID)                     #按键的虚拟键值   print('ScanCode:', event.ScanCode)               #按键扫描码   print('Extended:', event.Extended)               #判断是否为增强键盘的扩展键   print('Injected:', event.Injected)   print('Alt', event.Alt)                          #是某同时按下Alt   print('Transition', event.Transition)            #判断转换状态   print('---')   # 同上   return True


如果想了解具体含义,可以参考windows编程中的相关消息及参数含义。其实这些里大多就是上面提到的KeyBoardEvent类中设置的一些属性。MessageName字段描述事件的名称,Message则是事件类型的编号,Time就是事件发生时间,Window是事件发生在的窗口的编号,Ascii是按键内容的ASCII码,如果不属于ASCII字符集则为0,Extended描述是否是拓展键(比如Fn+一些键用来调电脑音量,屏幕亮度等就是扩展键),Alt是指出了按键是否是Alt键(存疑。。)若是则值为32,等等……

3. 绑定事件处理函数

复制代码
1
2
hm.MouseAllButtonsDown = OnMouseEvent #将OnMouseEvent函数绑定到MouseAllButtonsDown事件上 hm.KeyDown = OnKeyboardEvent          #将OnKeyboardEvent函数绑定到KeyDown事件


除此之外,还有以下事件:
鼠标事件:
MouseAll
MouseAllButtons
MouseAllButtonsUp
MouseAllButtonsDown
MouseAllButtonsDbl
MouseWheel
MouseMove
MouseLeftUp
MouseLeftDown
MouseLeftDbl
MouseRightUp
MouseRightDown
MouseRightDbl
MouseMiddleUp
MouseMiddleDown
MouseMiddleDbl
键盘事件:
KeyUp
KeyDown
KeyChar
KeyAll
因为都可以顾名思义,也就不再做注释。

4. 设置钩子

复制代码
1
2
hm.HookMouse()        #设置鼠标钩子 hm.HookKeyboard()   #设置键盘钩子


5. 循环监听
对于命令行界面的编程,设置了钩子后还不够,因为脚本在成功挂钩后,就结束运行了。这个时候就需要使程序进入循环监听系统事件的状态。
比较简单的方法是使用Win32 Extensions package提供的PumpMessages()方法:

复制代码
1
2
3
  import pythoncom   pythoncom.PumpMessages()


但是这个函数不是PyHook编程中必需的。如果是基于某些GUI库的编程,则不需要这样,因为GUI库本身就具有监听消息循环的机制。

6. 取消钩子

复制代码
1
2
hm.UnhookMouse()    #取消鼠标钩子 hm.UnhookKeyboard() #取消键盘钩子

完整案例:

复制代码
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import pythoncom import pyHook class KeyBoardManager(): keyIsPressed = False def onKeyDown(self,event): print('envent is ',event) if self.keyIsPressed: return True print(str(event.Key)+' is pressed') print('Ascii:',event.Ascii) print('MessageName:', event.MessageName) # 同上,共同属性不再赘述 print('Message:', event.Message) print('Time:', event.Time) print('Window:', event.Window) print('WindowName:', event.WindowName) print('Ascii:', event.Ascii, chr(event.Ascii)) # 按键的ASCII码 print('Key:', event.Key) # 按键的名称 print('KeyID:', event.KeyID) # 按键的虚拟键值 print('ScanCode:', event.ScanCode) # 按键扫描码 print('Extended:', event.Extended) # 判断是否为增强键盘的扩展键 print('Injected:', event.Injected) print('Alt', event.Alt) # 是某同时按下Alt print('Transition', event.Transition) # 判断转换状态 print('---') self.keyIsPressed = True return True def onKeyUp(self,event): self.keyIsPressed =False print(str(event.Key)+ ' is released') print('Ascii:', event.Ascii) print('MessageName:', event.MessageName) # 同上,共同属性不再赘述 print('Message:', event.Message) print('Time:', event.Time) print('Window:', event.Window) print('WindowName:', event.WindowName) print('Ascii:', event.Ascii, chr(event.Ascii)) # 按键的ASCII码 print('Key:', event.Key) # 按键的名称 print('KeyID:', event.KeyID) # 按键的虚拟键值 print('ScanCode:', event.ScanCode) # 按键扫描码 print('Extended:', event.Extended) # 判断是否为增强键盘的扩展键 print('Injected:', event.Injected) print('Alt', event.Alt) # 是某同时按下Alt print('Transition', event.Transition) # 判断转换状态 print('---') return True def onMouseEvent(event): print ("MessageName:",event.MessageName) print ("Message:", event.Message) print ("Time:", event.Time) # print ("Window:", event.Widow) print ("WindowName:", event.WindowName) print ("Position:", event.Position) print ("Wheel:", event.Wheel) print ("Injected:", event.Injected) print("---") return True if __name__ =="__main__": mykbmanager = KeyBoardManager() # 创建一个“钩子”管理对象 hookmanager = pyHook.HookManager() #监控键盘操作 hookmanager.KeyDown= mykbmanager.onKeyDown hookmanager.KeyUp = mykbmanager.onKeyUp # 设置键盘“钩子” hookmanager.HookKeyboard() #监控鼠标操作 # hookmanager.MouseAll = onMouseEvent # 设置鼠标“钩子” # hookmanager.HookMouse() # 循环获取信息 pythoncom.PumpMessages()

完整案例2:

复制代码
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
46
47
48
49
50
51
52
53
54
55
56
57
58
# -*- coding: utf-8 -*- from ctypes import * import pythoncom import PyHook3 import win32clipboard user32 = windll.user32 kernel32 = windll.kernel32 psapi = windll.psapi current_window = None # def get_current_process(): # 获取最上层的窗口句柄 hwnd = user32.GetForegroundWindow() # 获取进程ID pid = c_ulong(0) user32.GetWindowThreadProcessId(hwnd, byref(pid)) # 将进程ID存入变量中 process_id = "%d" % pid.value # 申请内存 executable = create_string_buffer(bytes.fromhex("00") * 512) h_process = kernel32.OpenProcess(0x400 | 0x10, False, pid) psapi.GetModuleBaseNameA(h_process, None, byref(executable), 512) # 读取窗口标题 windows_title = create_string_buffer(b"x00" * 512) length = user32.GetWindowTextA(hwnd, byref(windows_title), 512) # 打印 print("[ PID:%s-%s-%s]" % (process_id, executable.value, windows_title.value)) # 关闭handles kernel32.CloseHandle(hwnd) kernel32.CloseHandle(h_process) # 定义击键监听事件函数 def KeyStroke(event): global current_window # 检测目标窗口是否转移(换了其他窗口就监听新的窗口) if event.WindowName != current_window: current_window = event.WindowName # 函数调用 get_current_process() # 检测击键是否常规按键(非组合键等) if event.Ascii > 32 and event.Ascii < 127: print(chr(event.Ascii)), else: # 如果发现Ctrl+v(粘贴)事件,就把粘贴板内容记录下来 if event.Key == "V": win32clipboard.OpenClipboard() pasted_value = win32clipboard.GetClipboardData() win32clipboard.CloseClipboard() print("[PASTE]-%s" % (pasted_value)), else: print("[%s]" % event.Key), # 循环监听下一个击键事件 return True # 创建并注册hook管理器 kl = PyHook3.HookManager() kl.KeyDown = KeyStroke # 注册hook并执行 kl.HookKeyboard() pythoncom.PumpMessages()

参考:

https://blog.csdn.net/qq_37193537/article/details/90721115

https://www.jb51.net/article/146800.htm

https://www.cnblogs.com/franknihao/p/7904434.html

https://blog.csdn.net/q871063970/article/details/86648386

最后

以上就是悦耳衬衫最近收集整理的关于PyHook3实现监控键盘鼠标操作1. 创建HookManager对象的全部内容,更多相关PyHook3实现监控键盘鼠标操作1.内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(97)

评论列表共有 0 条评论

立即
投稿
返回
顶部