Detecting Mouse clicks in windows using python

The only way to detect mouse events outside your program is to install a Windows hook using SetWindowsHookEx. The pyHook module encapsulates the nitty-gritty details. Here’s a sample that will print the location of every mouse click:

import pyHook
import pythoncom

def onclick(event):
    print event.Position
    return True

hm = pyHook.HookManager()
hm.SubscribeMouseAllButtonsDown(onclick)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()

You can check the example.py script that is installed with the module for more info about the event parameter.

pyHook might be tricky to use in a pure Python script, because it requires an active message pump. From the 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.

Leave a Comment