gpt4 book ai didi

python - pyHook KeyLogger 线程未完成

转载 作者:太空宇宙 更新时间:2023-11-04 01:17:26 26 4
gpt4 key购买 nike

我为键盘记录器创建了一个线程,该线程与另一个产生一些声音的线程并行记录(我想捕捉 react 时间)。

不幸的是,尽管我调用了 killKey() 并打印了“invoked killkey()”,但线程从未完成。

我总是从这个线程得到一个 thread.isActive() = true。

class KeyHandler(threading.Thread):
hm = pyHook.HookManager()

def __init__(self):
threading.Thread.__init__(self)

def OnKeyboardCharEvent(self,event):
print 'Key:', event.Key
if event.Key=='E':
...
return True

def killKey(self):
KeyHandler.hm.UnhookKeyboard()
ctypes.windll.user32.PostQuitMessage(0)
print "invoked killkey()"

def run(self):
print "keyHandlerstartetrunning"
KeyHandler.hm.KeyDown = self.OnKeyboardCharEvent
KeyHandler.hm.HookKeyboard()
#print "keyboardhooked"
pythoncom.PumpMessages()

更准确地说,ctypes.windll.user32.PostQuitMessage(0) 什么都不做

我希望使用外部超时来调用 killKey(),以及该线程中的相应 ctypes.windll.user32.PostQuitMessage(0)。

最佳答案

PostQuitMessage 必须从同一个线程发布。为此,您需要引入一个全局变量 STOP_KEY_HANDLER。如果您想退出,只需从您想要的任何线程设置全局 STOP_KEY_HANDLER = True,它将在下一次击键时退出。您的 key 处理程序必须在主线程上运行。

STOP_KEY_HANDLER = False

def main():
pass # here do all you want
#bla bla
global STOP_KEY_HANDLER
STOP_KEY_HANDLER = True # This will kill KeyHandler


class KeyHandler:
hm = pyHook.HookManager()

def OnKeyboardCharEvent(self,event):
if STOP_KEY_HANDLER:
self.killKey()
print 'Key:', event.Key
if event.Key=='E':
pass
return True

def killKey(self):
global STOP_KEY_HANDLER
if not STOP_KEY_HANDLER:
STOP_KEY_HANDLER = True
return None
KeyHandler.hm.UnhookKeyboard()
ctypes.windll.user32.PostQuitMessage(0)
print "invoked killkey()"

def _timeout(self):
if self.timeout:
time.sleep(self.timeout)
self.killKey()

def run(self, timeout=False):
print "keyHandlerstartetrunning"
self.timeout = timeout
threading.Thread(target=self._timeout).start()

KeyHandler.hm.KeyDown = self.OnKeyboardCharEvent
KeyHandler.hm.HookKeyboard()
#print "keyboardhooked"
pythoncom.PumpMessages()


k=KeyHandler()

threading.Thread(target=main).start()
k.run(timeout=100) # You can specify the timeout in seconds or you can kill it directly by setting STOP_KEY_HANDLER to True.

关于python - pyHook KeyLogger 线程未完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23516150/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com