pyHook键盘记录器线程未完成

2024-04-23 18:59:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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

不幸的是,尽管我调用了killKey()并打印了“invoked killKey()”,但线程始终没有完成。在

我总是得到一个线程激活()=来自此线程。在

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)在此线程中。在


Tags: keyselfeventdefctypes线程printthreading
1条回答
网友
1楼 · 发布于 2024-04-23 18:59:00

我想pbackup的解决方案很好。最后,我找到了一个解决方案,只需自己发送一个密钥,而不是等待用户输入。它不是最好的,但却是最快的,在我的计时线程与其他计时例程并行。在

    STOP_KEY_HANDLER = True

    # send key to kill handler - not pretty but works
    for hwnd in get_hwnds_for_pid (GUIWINDOW_to_send_key_to.pid):
        win32gui.PostMessage (hwnd, win32con.WM_KEYDOWN, win32con.VK_F5, 0)
    # sleep to make sure processing is done
    time.sleep(0.1)

    # kill window
    finished()
网友
2楼 · 发布于 2024-04-23 18:59:00

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

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.

相关问题 更多 >