【问题标题】:Squelching keyboard input when modifier is held down with pynput on Windows在 Windows 上使用 pynput 按住修饰符时静噪键盘输入
【发布时间】:2018-10-09 23:23:11
【问题描述】:

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

【问题讨论】:

  • 这更像是一个pynput 问题而不是 Python 问题——理想情况下,标题和标签应该反映这一点。在添加一个可以执行特定于操作系统的 I/O 操作的库之前,所有基本级别的运行时支持都是 TTY 样式的终端输入,它根本不提供修饰符 的键向上/向下键信息.

标签: python python-3.x pynput


【解决方案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

【讨论】:

    猜你喜欢
    • 2015-11-17
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 2017-12-07
    • 2016-03-06
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    相关资源
    最近更新 更多