在Windows上使用Pynput按下修改器时压制键盘输入

时间:2018-10-07 07:55:35

标签: python python-3.x pynput

我有一个简单的脚本,用于查找某些按键组合。找到它们后,它将它们写入文件。我正在使用`作为修饰符。例如,如果我执行“ + 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()

1 个答案:

答案 0 :(得分:0)

好的,所以我找不到使用Python做到这一点的方法。我确信这是有可能的,但我无法弄清楚!无论如何,由于计算机运行的是Windows,所以我决定使用AutoHotkey进行操作。这样做很简单,而且像一种魅力。

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

我决定使用一个切换键,该切换键在按下时会捕获所有键盘输入。再次按下切换键,脚本将被挂起,所有命令都将转到活动窗口。

#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