Python Keyboard Module add_hotkey is not working after you lock windows Once. Help Needed

1.6k views Asked by At

This is the code that is working until I press windows+L to lock my windows PC. Once I lock my PC and then unlock it, the hotkeys stop working and the terminal window is hung. I have to exit the program by keyboard interrupt. Here is the working or not-working code.

import sys
from keyboard import add_hotkey

def keyDetector():

    add_hotkey('ctrl+F2', ctrl_f2)   
    add_hotkey('ctrl+F3', ctrl_f3)   
    add_hotkey('ctrl+F4', ctrl_f4)
    add_hotkey('ctrl+F12', ctrl_f12) 
    add_hotkey('windows+l', win_l)

    while not exit:
        sleep(1)

def ctrl_f2():
    print(" You pressed control + F2.")


def ctrl_f3():
    print(" You pressed control + F3.")


def ctrl_f4():
    print(" You pressed control + F4.")


def ctrl_f12():
    global exit
    print(" You have pressed control + F12, exiting the program now.")
    exit = True
    sys.exit()


def win_l():
    print(" You pressed Windows + L.")

I would like to point out once again that when I run the code, everything works fine until I lock my windows and then unlock it, that is when everything goes awry.

1

There are 1 answers

0
Aaron Jones On BEST ANSWER

This is how I solved my issue.

I ditched the keyboard module since it was not working the way I wanted it to and then I used the Python Global-Hotkeys Module. The code was pretty much the same but now everything just clicked in place.

Hope this helps someone in the future. Here is the modified code.

import sys
from global_hotkeys import *

is_alive = True


def ctrl_f2():
    print(" You pressed control + F2.")


def ctrl_f3():
    print(" You pressed control + F3.")


def ctrl_f6():
    print(" You pressed control + F4.")


def ctrl_f12():
    global is_alive
    print(" You have pressed control + F12, exiting the program now.")
    is_alive = False
    sys.exit()



bindings = [
    [["control", "f2"], None, ctrl_f2],
    [["control", "f3"], None, ctrl_f31],
    [["control", "f6"], None, ctrl_f6],
    [["control", "f12"], None, ctrl_f12],
]

while is_alive:
    sleep(0.1)