排除子进程时的线程

2024-05-08 14:35:25 发布

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

我写了一个程序,捕捉俄罗斯方块上的键盘事件,它是通过一个子进程打开的。不当我只想捕捉事件而不打开俄罗斯方块时,我的键盘处理程序(pyHook)不会捕捉事件:

# open Tetris
#Tetris = subprocess.Popen (["C:\\Program Files (x86)\Tetris\Tetris.exe"])
#start game by sending "F2" key
#for hwnd in get_hwnds_for_pid (Tetris.pid):
    #win32gui.PostMessage (hwnd, win32con.WM_KEYDOWN, win32con.VK_F2, 0)

keyH = KeyHandler()
ToneT = ToneTimer()

keyH.setDaemon(True)
ToneT.setDaemon(True)

keyH.start()
ToneT.start()

当使用另一个子进程时,这工作得很好,但我不知道为什么现在卡住了。钥匙处理者拿不到钥匙。你知道吗

class KeyHandler(threading.Thread):

    def run(self):
        # 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"

除最后一条语句外,所有语句都会被打印,但不会打印诱发的键,而是当我按下某个键时,应用程序会冻结(我有一个函数,可以捕捉与包含的子进程一起工作的事件…)

我猜在省略子进程时线程有问题。你知道吗

我发现如果我在按下一个键之前切换到另一个GUI窗口,然后按下一个键,键就会被接受并打印keyevents。你知道吗

更准确的信息:这可能与在OpenSesame(实验软件)内部运行脚本有关,因为pyhook通常不会从他的窗口检索键盘响应,而只从gui窗口?!因此,我可能需要寻找一个替代品pyhook在这里?你知道吗


Tags: for进程事件键盘pidstarttetris方块
2条回答

它不工作,因为Qt绕过windows消息循环pyHook依赖于消息循环来运行。你知道吗

Modern graphical interface frameworks, such as Windows Forms, Windows Presentation Foundation, MFC, Delphi, Qt and others do not typically require applications to directly access the Windows message loop, but instead automatically route events such as key presses and mouse clicks to their appropriate handlers as defined within the framework.

Message Loop in MS Windows

run方法需要有一个循环。线程一旦离开run方法就结束了。你知道吗

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

或者你根本不必给它分类。你知道吗

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.

相关问题 更多 >