pynput: Listen only if window is active

70 Views Asked by At

When I set suppress=True on pynput.keyboard.Listener and minimize my program window, it blocks the system from listening to the keyboard.

Is it possible to block the system from listening to the keyboar only when my program window is active?

1

There are 1 best solutions below

0
5rod On

You can use pywinctl, which works on Linux, MacOS, and of course Windows. Here I've incorporated the pynput listener into a loop, where a function checks if the window is open or closed. Here's a snippet of code:

from pynput.keyboard import Listener
import pywinctl

def py_is_opened():
    if program_window_name == pywinctl.getActiveWindowTitle():
        return True
    else:
        return False

def on_press(key):
    if not py_is_opened(): #if the window is not opened (closed currently)
        return False #stops the listener
    
    #do stuff with key

while True:
    with Listener(on_press=on_press, suppress=True) as listener:
        listener.join()
    
    while True:
        if py_is_opened():
            break #start the listener again if program is opened

This code checks whether the window is opened, if it is, then it suppresses keyboard input and listens for it. If not, the program does not suppress key presses, and does not listen for any keyboard input. Note that you need to replace the variable program_window_name with the name of your program, in my case, it is: '*IDLE Shell 3.12.1*'. To figure it out, run this simple test:

import pywinctl

print(pywinctl.getActiveWindowTitle())

Remember to keep your program the active window when you run this program. Then, you will see your window title. Simply replace the variable with the window title that you got from this program, and everything should work as planned.