在 Windows 上使用 pynput 按住修饰符时抑制键盘输入

Squelching keyboard input when modifier is held down with pynput on Windows

我有一个简单的脚本来查找特定的组合键。当找到它们时,它会将它们写入文件。我使用 ` 作为修饰符。例如,如果我执行 `+x,那么 "x" 将被写入文件。

我的问题是键盘输入也被发送到任何 window 处于活动状态。我不想要那个。我只想在按住 ` 时将输入发送到文件。有办法吗?

编辑:我也可以将键盘笔画重定向到特定的 window,比如在后台打开记事本,如果这样会更容易的话。

这是脚本。它在 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()

好的,所以我无法使用 Python 找到执行此操作的方法。我确信这是可能的,但我想不通!无论如何,计算机是 运行 Windows 所以我决定用 AutoHotkey 来做。这很简单,但效果很好。

编辑:这是示例 AHK 脚本。我知道这个答案并不真正属于 Python 部分,但希望它能帮助任何通过 Google 找到它的人 :)

我决定使用切换键,按下时将捕获所有键盘输入。再次按下切换键时,脚本将暂停,所有命令将转到 window 处于活动状态的那个。

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.

SetWorkingDir C:\ahkscripts

; Use capslock as a toggle key
capslock::
    Suspend
return

; write "1" to a file. FileAppend will create the file if it doesn't exist
1::
    FileAppend, `n1, *myoutputfile.txt, 
return



; write alt+1 to a file
!1::
    FileAppend, `naltleft 1, *myoutputfile.txt, 
return


; write shift+1 to a file

+1::
    FileAppend, `nshiftleft 1, *myoutputfile.txt, 
return