0

我有一个简单的脚本来查找某些组合键。当它们被发现时,它会将它们写入文件。我使用 ` 作为修饰符。例如,如果我执行 `+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()
4

1 回答 1

1

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

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

我决定使用一个切换键,当它被按下时将捕获所有键盘输入。当再次按下切换键时,脚本将暂停,所有命令都会转到处于活动状态的任何窗口。

#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
于 2018-10-09T15:01:59.380 回答