keyboard icon indicating copy to clipboard operation
keyboard copied to clipboard

add_hotkey fails after locking and unlocking Windows

Open happyTonakai opened this issue 2 years ago • 3 comments

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.

happyTonakai avatar Feb 15 '23 08:02 happyTonakai

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.

jeremydrahos avatar Dec 11 '23 17:12 jeremydrahos

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.

RandomGgames avatar Jan 08 '24 21:01 RandomGgames

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

richiehowelll avatar Jun 30 '24 02:06 richiehowelll