在程序外部检测鼠标事件的唯一方法是使用
SetWindowsHookEx安装Windows钩子.
pyHook模块封装了细节细节。以下是一个示例,它将打印每次鼠标点击的位置:
import pyHook
import pythoncom
def onclick(event):
print event.Position
return True
hm = pyHook.HookManager()
hm.SubscribeMouseAllButtonsDown(onclick)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()
您可以检查与模块一起安装的example.py脚本,以获取有关event参数的更多信息。
因为pyHook需要一个活动的消息泵,所以pyHook可能会在纯Python脚本中使用很棘手。从tutorial:
Any application that wishes to receive notifications of global input events must have a Windows message pump. The easiest way to get one of these is to use the PumpMessages method in the Win32 Extensions package for Python. […] When run, this program just sits idle and waits for Windows events. If you are using a GUI toolkit (e.g. wxPython), this loop is unnecessary since the toolkit provides its own.