How do I use my own loop with pyhook instead of pumpMessages()?

Go To StackoverFlow.com

7

I'm trying to use pyhooks to detect mouse clicks anywhere on screen. The problem is that I can only get it to work with PumpMessages(). I'd like it operate inside of a while loop that I've constructed. Is there a way to accomplish this/why does it need pumpMessages?

def onclick(event):
    print 'Mouse click!'
    return True


hm = pyHook.HookManager()

hm.MouseLeftDown = onclick

hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()

The above is the only way I can get it to run.

I'm trying to accomplish something like this:

sTime = time.time()

def onclick(event):
    global sTime
    print 'Time between clicks equals: %i' % time.time() - stime
    sTime = time.time()
    return True

hm.MouseLeftDown = OnClick

while True:

    hm.HookMouse()

EDIT: I am not a smart man. There is no need for a while loop in the scenario..

Sigh..

2012-04-04 03:47
by Zack


3

From the pyhook tutorial:

Any application that wishes to receive notifications of global input events must have a Windows message pump.

However, this shouldn't necessarily prevent your code from working. Why don't you post what you are trying to do, and we can look for a way to use the message pump in the context of your code.

One way you might be able to solve your problem is through PostQuitMessages(original solution here)

import ctypes
ctypes.windll.user32.PostQuitMessage(0)
2012-04-04 03:58
by Nolen Royalty


14

Just for future reference, you can use pythoncom.PumpWaitingMessages() inside the while loop, since it does not lock the execution. Something like this:

while True:
    # your code here
    pythoncom.PumpWaitingMessages()
2013-01-10 00:51
by Matheus Portela
that is the right answer, nothing els - Muppet 2013-05-17 02:26
Agree with Muppet. This should be the correct answer. Thanks for this I searched quite a while before finding this simple solution - SeanDav 2016-06-22 23:42
but isn't that hogging the CPU since it's non-blocking - Jean-François Fabre 2017-05-23 09:23
It depends on what your code is doing. In my code, for instance, I needed to check many things before pumping messages, so I couldn't be blocked in the PostQuitMessage call - Matheus Portela 2018-01-08 16:54
Ads