擅长:python、mysql、java
<p>run方法需要有一个循环。线程一旦离开run方法就结束了。你知道吗</p>
<pre><code>class KeyHandler(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.running = True
# end
def run(self):
while self.running:
# watch for all keyboard events
KeyHandler.hm.KeyDown = self.OnKeyboardCharEvent
# set the hook
KeyHandler.hm.HookKeyboard()
# activate message pipeline
print "keyboardhooked"
pythoncom.PumpMessages()
print "thisshouldnotbeprinted"
# end run
</code></pre>
<p>或者你根本不必给它分类。你知道吗</p>
<pre><code>def catch_key(keyboard):
# watch for all keyboard events
KeyHandler.hm.KeyDown = keyboard.OnKeyboardCharEvent
# set the hook
KeyHandler.hm.HookKeyboard()
# activate message pipeline
print "keyboardhooked"
pythoncom.PumpMessages()
print "thisshouldnotbeprinted"
thread = threading.Thread(target=catch_key, args=(Keyboard()))
thread.start()
# Remember to use thread.join() to safely close the thread.
</code></pre>