Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with pyHook error

Tags:

python

windows

I'm trying to make a global hotkey with pyhook in python that is supposed to work only with the alt key pressed.

here is the source:

import pyHook
import pythoncom

hm = pyHook.HookManager()

def OnKeyboardEvent(event):
    if event.Alt == 32 and event.KeyID == 49:
        print 'HERE WILL BE THE CODE'

hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages()

but when I execute, only works with the second press of the second key (number 1 = 49)... and give this error:

http://img580.imageshack.us/img580/1858/errord.png

How can I solve it? For work at the first pressed time.

like image 827
Bruno 'Shady' Avatar asked Jan 21 '23 21:01

Bruno 'Shady'


1 Answers

Note from the tutorial that you need a return value at the end of your handler:

def OnKeyboardEvent(event):
    if event.Alt == 32 and event.KeyID == 49:
        print 'HERE WILL BE THE CODE'

    # return True to pass the event to other handlers
    return True

I agree it's ambiguous from the docs whether that's required, but you do need to return True or False (or possibly any integer value), with any "false" value (e.g. 0) blocking the event such that no subsequent handlers get it. (This lets you swallow certain keystrokes conditionally, as in the Event Filtering section of the tutorial.)

(This wasn't as easy to figure out as it might look! :-) )

like image 199
Peter Hansen Avatar answered Jan 30 '23 01:01

Peter Hansen