Search code examples
pythonpython-3.xwindowkeyboard-events

How to listen to pressed keys of a specific window


I want to print only the keys that've been pressed in "Google Chrome" .i've searched a lot didn't find anything. Need example code or smthg

idk my code:

import win32com.client as comctl
wsh = comctl.Dispatch("WScript.Shell")
wsh.AppActivate("Youtube - Google Chrome") # Google Chrome window title
wsh.SendKeys("{O}")
print(akeyhasbeenpressed) # :/

Solution

  • Very interesting question indeed.

    I've read the win32com docs (http://timgolden.me.uk/pywin32-docs/html/com/win32com/HTML/QuickStartClientCom.html#Using) and I figured out that the module does not seem to implement a listener for key presses.

    However, a possible solution for your problem consists in using win32gui and pynput modules like this:

    import win32gui
    from pynput import keyboard
    
    def on_press(key):
         try: key_pressed = key.char # single-char keys
         except: key_pressed = key.name # other keys
         print(key_pressed)
         active_window = win32gui.GetWindowText(win32gui.GetForegroundWindow())
         print(active_window)
          
    listener = keyboard.Listener(on_press=on_press)
    listener.start() 
    listener.join() 
    

    The keyboard listener handles the key press event, whereas win32gui gives you the active window name at the time of key press.

    Of course, you can then easily filter by the window that you're interested in:

    def on_press(key):
     try: key_pressed = key.char # single-char keys
     except: key_pressed = key.name # other keys
     active_window = win32gui.GetWindowText(win32gui.GetForegroundWindow())
     if active_window == "Youtube - Google Chrome":
          # ... 
          # do something
          # ...