boppreh / keyboard

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

hot_key not triggered in multi_threading environment #597

Open latesnow opened 1 year ago

latesnow commented 1 year ago

I'm trying to write a multi-threaded program where one thread is dong a task on the background. Once a hotkey is pressed, the whole program should be terminated. The script I tested is as below:

keyboard.add_hotkey('p', key_pressed)
while flag:
    time.sleep(1)

function key_pressed prints a message and sets flag to False on invocation. The above script works. But if I change it to:

t = Thread(target=show_position)
t.run()
keyboard.add_hotkey('p', key_pressed)
while flag:
    time.sleep(1)

No msg is printed and the program never stops. Does anyone have any idea about this?