Littlegator
Littlegator

Reputation: 395

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?

Upvotes: 1

Views: 4162

Answers (3)

a door
a door

Reputation: 11

You can do this using keyboard too

import keyboard


def on_key_event(event):
    if event.name == 'z':
        return
    # for the keys we don't want to suppress, we just send the events back out
    if event.event_type == 'down':
        keyboard.press(event.name)
    else:
        keyboard.release(event.name)


keyboard.hook(on_key_event, suppress=True)

keyboard.wait('esc')

Upvotes: 1

Osama Adel
Osama Adel

Reputation: 238

from pynput import keyboard # 1
def on_key_press(key): # 2
    print(f'Key {key} pressed') # 3
listener = keyboard.Listener(on_press=on_key_press) # 4
import keyboard # 4.1
keyboard.block_key('a') # 4.2
listener.start() # 5
listener.join() # 6

This code captures all the pressed keys and prevents the key 'a' from affecting any other application other than this Python app.

Upvotes: 0

entrez
entrez

Reputation: 301

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.

Upvotes: 3

Related Questions