Search code examples
pythonautomationkeyboardkeyboard-events

How to execute a function before key press?


I'm trying to append "🗿🍷" to everything I write as a challenge to live a week with that enabled. It's quite easy to send "🗿🍷" after the fact with the keyboard module, but what I want to achieve is sending it before I press the enter key.

Here's my current code:

# it still sends it after the enter keypress
import keyboard


def on_enter_press(event):
    if event.name == "enter":
        keyboard.block_key("enter")

        keyboard.write("🗿🍷")

        keyboard.unhook_all()
        keyboard.press_and_release("enter")


keyboard.hook_key("enter", on_enter_press)

keyboard.wait("esc")

Solution

  • On Windows only, you can use suppress=True in many keyboard functions to suppress the original enter press before re-sending it-- the following code works on my machine:

    import keyboard
    
    def on_enter_press():
        keyboard.write("🗿🍷", exact=True)
        keyboard.press_and_release("enter")
    
    keyboard.add_hotkey('enter', on_enter_press, suppress=True)