我想检测按键是否以编程方式执行(而不是通过用户的物理按键)。有什么办法可以做到吗?
import mouse
import keyboard
import time
keyboard.press("a")
if keyboard.is_pressed('a'):
print ("pressed")
我假设上面代码中的'is_pressed'只检测用户的实际输入,因此它不会显示print ("pressed")。为了解决这个问题,我所能想到的就是下面的代码,它对我的意图来说很好,但我想知道是否有更好的优化方法。
import mouse
import keyboard
import time
keyboard.press("a")
keyboard_a = True
keyboard.press("b")
keyboard_b = True
if keyboard_a:
print ("a pressed")
if keyboard_b:
print ("b pressed")
无法区分由编程触发的按键事件和由用户输入触发的按键事件。对于readchar
,msvcrt
或keyboard
库也是如此。
因此,库提供了一种检测和响应按键事件的方法,而不管它们的来源是什么。因此,您使用标志的方法是好的。
我不知道你的精确目标,但也许你更喜欢使用send
和像这样的寄存器事件
import keyboard
import threading
is_programmatic = False
# Define a function to be called when a specific key is pressed
def on_key_press(keyEvent):
global is_programmatic
if keyEvent.name == 'a':
if is_programmatic:
print("Key press event triggered programmatically")
else:
print("Key press event triggered by user input")
is_programmatic = False
# Register listener
keyboard.on_press(on_key_press)
# Start keyboard listener
keyboard.wait()
# or start a thread with the listener (you may want to sleep some seconds to wait the thread)
thread = threading.Thread(target=keyboard.wait)
thread.start()
和发出事件
is_programmatic = True
keyboard.send("a")
您可以创建一个列表并在该列表中存储按下的键。您可以通过搜索该列表来查找是否按下了某个键。
import keyboard
key_pressed = []
keyboard.press("a")
key_pressed.append("a")
keyboard.press("b")
key_pressed.append("b")
keyboard.press("c")
key_pressed.append("c")
#check if a specific key is pressed
if "a" in key_pressed:
print ("a pressed")
打印所有按下的键:
for key in key_pressed:
print(key,'pressed')
打印最后按下的键:
print(key_pressed[-1])
您还可以创建一个类,使其更易于使用:
import keyboard
class CustomKeyboard():
def __init__(self):
self.pressed_keys = []
def press(self, key):
keyboard.press(key)
self.pressed_keys.append(key)
def is_pressed_programmatically(self, key):
if key in self.pressed_keys:
return True
return False
然后像这样使用:
kb = CustomKeyboard()
kb.press('a')
kb.press('b')
print("did a pressed programmatically?:")
print(kb.is_pressed_programmatically('a'))
print("did z pressed programmatically?:")
print(kb.is_pressed_programmatically('z'))
,下面是输出:
是程序按下的?:真正的
是按z键编程的吗?:假