PyHook3典型代码
from ctypes import *
import PyHook3 as pyHook
import pythoncom
def onKeyboardEvent1(event): print("onKeyboardEvent") pid = c_ulong(0) windowTitle = create_string_buffer(512) windll.user32.GetWindowTextA(event.Window, byref(windowTitle), 512) windll.user32.GetWindowThreadProcessId(event.Window, byref(pid)) windowName = windowTitle.value.decode('gbk') print("当前您处于%s窗口" % windowName) print("当前窗口所属进程id %d" % pid.value) print("当前刚刚按下了{}键, ascii值为{}, KeyID = {}, ScanCode = {}".format(chr(event.Ascii), str(event.Ascii), event.KeyID, event.ScanCode)) 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)) print("Key:", event.Key) print("KeyID:", event.KeyID) print("ScanCode:", event.ScanCode) print("Extended:", event.Extended) print("Injected:", event.Injected) print("Alt", event.Alt) print("Transition", event.Transition) print("---------") #返回 True 以便将事件传给其它处理程序, 这儿如果返回 False ,则事件将被全部拦截 return True def onMouseEvent(event): # 监听鼠标事件 print("MessageName:",event.MessageName) print("Message:", event.Message) 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("--------------------------------------------------------------------------------") return True hm = pyHook.HookManager() #hm.KeyDown = onKeyboardEvent #hm.HookKeyboard() #hm.MouseAllButtons = onMouseEvent hm.MouseWheel = onMouseEvent hm.HookMouse() pythoncom.PumpMessages()