Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

python - Help with pyHook error

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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! :-) )


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...