[python-win32] hook the left mouse button down event on any window

Tim Roberts timr at probo.com
Sat Mar 30 15:24:25 EDT 2019


On Mar 29, 2019, at 8:39 PM, Zhao Lee <redstone-cold at 163.com> wrote:
> 
> import win32gui
> import win32ui
> import win32con
> 
> def onMousePressed(self):
>     print('onMousePressed', win32gui.GetCursorPos())
> 
> def listener():
>     windowHandle = win32gui.WindowFromPoint(win32gui.GetCursorPos())
>     clickedWindow = win32ui.CreateWindowFromHandle(windowHandle)
>     clickedWindow.HookMessage(onMousePressed, win32con.WM_LBUTTONDOWN)
>     # print('-------------registerMouseEvent', clickedWindow)
> 
> while True:
>     listener()
>     time.sleep(8)
> 
> what is wrong and what's the good practice ?

I TOLD you what is wrong.  Let’s follow the flow.  Every 8 seconds you call listener.  It does the following, very quickly:

* Fetch the window under the cursor, assuming the cursor is over a window.
* Create a Python window object around that window handle
* Install a hook to catch button down messages for that specific window
* Function exits, the window object is destroyed, and the hook is uninstalled

Then you go back to sleep.  While you are alseep, there is no hook.  The only time you have a hook is the few milliseconds between your HookMessage call and when the function returns.

The right answer is to use a package like pyHook to install a global hook.  This is exactly what it is for.

https://stackoverflow.com/questions/165495/detecting-mouse-clicks-in-windows-using-python <https://stackoverflow.com/questions/165495/detecting-mouse-clicks-in-windows-using-python>
— 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-win32/attachments/20190330/6266aed5/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 3870 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-win32/attachments/20190330/6266aed5/attachment.bin>


More information about the python-win32 mailing list