0

这是一直有效的代码,直到我按下 windows+L 来锁定我的 windows PC。一旦我锁定我的电脑然后解锁它,热键就会停止工作并且终端窗口会挂起。我必须通过键盘中断退出程序。这是工作或不工作的代码。

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.")

我想再次指出,当我运行代码时,一切正常,直到我锁定我的窗户然后解锁它,这就是一切都出错的时候。

4

1 回答 1

0

这就是我解决问题的方法。

我放弃了键盘模块,因为它没有按照我想要的方式工作,然后我使用了Python Global-Hotkeys Module。代码几乎相同,但现在一切都已到位。

希望这对将来的某人有所帮助。这是修改后的代码。

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)
于 2021-05-30T07:55:26.680 回答