boppreh / keyboard

Hook and simulate global keyboard events on Windows and Linux.
MIT License
3.8k stars 433 forks source link

how to send a keystroke in order to trigger associated hotkey? #497

Open ThibaultVlieghe opened 3 years ago

ThibaultVlieghe commented 3 years ago

Hello!

Thanks a lot for this amazing module.

I would like to ask, how do I simulate a key press (say 'r') in order to trigger a hotkey (like: keyboard.add_hotkey('r', lambda: print('r was pressed!')))

The hotkey works perfectly when I type 'r' myself

but whenever I try to simulate an r keypress with python, the hotkey doesn't react. I've also tried other libraries to simulate keypresses, and they all work at actually typing r, but all fail at triggering the hotkey.

What am I doing wrong? I was certain this would work.

Thanks,


import keyboard

import pyautogui

from pynput.keyboard import Controller
pynput_keyboard = Controller()

import autopy

def on_r():
    print('r was pressed')
# there should be 'r was pressed' in the command line every time r is pressed
keyboard.add_hotkey('r', on_r)

while True:
    # pressing key r with keyboard.write
    keyboard.write('r')
    # pressing key r with keyboard.send
    keyboard.send('r', do_press=True, do_release=True)
    # pressing key r with keyboard.press
    keyboard.press('r')
    keyboard.release('r')

    # trying with pynput
    pynput_keyboard.press('r')
    pynput_keyboard.release('r')

    # trying with pyautogui
    pyautogui.press('r')

    # trying with autopy
    autopy.key.type_string('r')

    time.sleep(2.16)