1

我正在将 Pynput 和 Subprocess 与NirCmd一起使用,以创建一个可以关闭我的显示器的热键。第一次触发该功能时,该程序运行良好。但是,当第二次触发该功能时,按下任何 ctrl 键,即使是单独按下,也会触发该功能。这是我的代码:

import subprocess
from string import ascii_lowercase, digits
from pynput.keyboard import Key, KeyCode, Listener

#Function mapped to HotKey
def monitor_off():
    subprocess.run("ECHO Testing", shell=True) #<--- This is an example operation to show that the program works when doing anything other than running NirCmd
    #subprocess.run("nircmd monitor off", shell=True) '''<--- This is the problematic operation'''

#Combination to trigger the function monitor_off
combination_to_function = {
frozenset([Key.ctrl_l, Key.ctrl_r]): monitor_off,
}

#Creating set to store the keys being actively pressed
current_keys = set()

'''When a key is pressed, add it to the current_keys set.
Then check if the current_keys set matches any of the hotkey combinations.
If it does, execute the function mapped to the combination(s)'''
def on_press(key):
    current_keys.add(key)
    if frozenset(current_keys) in combination_to_function:
        combination_to_function[frozenset(current_keys)]()

#When a key is released, remove it from the current_keys set
def on_release(key):
    current_keys.remove(key)

#Joining on_press and on_release to the main thread
with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()
4

0 回答 0