boppreh / keyboard

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

add_hotkey fails after locking and unlocking Windows #595

Open happyTonakai opened 1 year ago

happyTonakai commented 1 year ago

Simple code could be:

import keyboard
import mouse
def click():
     mouse.click('left')
keyboard.add_hotkey('0', click, suppress=True)

after that, press win+L to lock the system and then enter the system again, the hotkey is not working anymore.

jeremydrahos commented 8 months ago

Has anyone found a workaround for this issue? I am also encountering it.

edit: after fiddling with a few things, like removing/re-adding the hotkey, I realized it seems more like the module itself is unresponsive. My crude workaround is to unload the module and reload it and reinitialize the hotkey on an interval. This interval length was more for testing, I'm sure it can be extended to something more realistic. This is specific to my application and should be changed to meet your needs.

import keyboard
import time
import threading
import sys

HOTKEY = 'ctrl+alt+shift+m'
exit_flag = False

def listener_loop():
    global exit_flag, HOTKEY
    while not exit_flag:
        try:
            keyboard.remove_hotkey(HOTKEY)
            sys.modules.pop('keyboard')
        except:
            pass

        import keyboard
        keyboard.add_hotkey(HOTKEY, on_hotkey)

        for _ in range(4):
            time.sleep(5)
            if exit_flag:
                break

listener_thread = threading.Thread(target=listener_loop)
listener_thread.start()

# at the end to let the thread finish before exit
listener_thread.join()

It's not the best, but it's working.

RandomGgames commented 7 months ago

I just ran into this issue. I hope it can be resolved, or add a method for detecting that the computer has been locked then unlocked.

richiehowelll commented 1 month ago

For those still dealing with this I found this solution to be better than popping the module and re-importing