pythonpython-3.xpyautoguipynput

How to prevent certain certain keys from "sending" input in Python


I'm trying to use Python to replace AutoHotkey. I've set up pynput to listen to keys and gotten most of everything to work as I'd expect. However, I have a problem where, if I "rebind" a key by listening to the keyboard and doing something on keypress, it still sends the original command. I don't understand things behind the scenes with DirectInput, let alone all the layers on top of this, so it's difficult to explain my question.

Example of what I want ("rebinding" F3 to a mouse click):

Press F3
Mouse click input is sent

Example of what happens:

Press F3
F3 input is sent
Mouse click input is sent

How can I prevent the superfluous key from being sent, so only my "rebound" actions are sent?


Solution

  • When you set up your keyboard listener with pynput, you should be able to set suppress = True; from the documentation:

    suppress (bool) – Whether to suppress events. Setting this to True will prevent the input events from being passed to the rest of the system.

    So for example, instead of this sample code from the documentation:

    # Collect events until released
    with keyboard.Listener(
            on_press=on_press,
            on_release=on_release) as listener:
        listener.join()
    

    You would modify it this way to block the events from being passed to the rest of the system:

    # Collect events until released
    with keyboard.Listener(
            suppress=True,
            on_press=on_press,
            on_release=on_release) as listener:
        listener.join()
    

    Note that there is not an option to block only certain keys, so if you want to block hotkeys and allow others to pass through you would probably want to set up a default case in the on_press callback to pass through by pressing the same key as was just registered via the same kind of keyboard.Controller mechanisms you are using to 'rebind' the hotkeys.