我有一个简单的脚本来查找某些组合键。当它们被发现时,它会将它们写入文件。我使用 ` 作为修饰符。例如,如果我执行 `+x 那么“x”将被写入文件。
我的问题是键盘输入也会发送到任何处于活动状态的窗口。我不想要那个。我只想在按住 ` 时将输入发送到文件。有没有办法做到这一点?
编辑:如果这样更容易的话,我也可以将键盘敲击重定向到特定窗口,比如在后台打开记事本。
这是脚本。它在 Windows 上使用 Python3。
import os
from pynput import keyboard
def main():
filename = "log.txt"
# The key combination to check
COMBINATIONS = [
# Alpha characters
{keyboard.KeyCode(char="`"), keyboard.KeyCode(char='x')},
{keyboard.KeyCode(char="`"), keyboard.KeyCode(char='X')}
]
current = set()
def execute(combo):
command = []
for item in combo:
try:
print(item.char)
command.append(item.char)
except AttributeError as e:
print(item.name)
command.append(item.name)
command = [c for c in command if c != "`"]
command = " ".join(sorted(command))
print(command)
fo = open(filename, "a+")
fo.write("{}\n".format(command))
def on_press(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
current.add(key)
if any(all(k in current for k in COMBO) for COMBO in COMBINATIONS):
print((k in current for k in COMBO) for COMBO in COMBINATIONS)
execute(current)
def on_release(key):
if any([key in COMBO for COMBO in COMBINATIONS]):
current.remove(key)
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
if __name__ == "__main__":
main()