使用 pynput 监听器创建键盘快捷键

Posted

技术标签:

【中文标题】使用 pynput 监听器创建键盘快捷键【英文标题】:Creating keyboard shortcuts with pynput listener 【发布时间】:2022-01-02 08:57:56 【问题描述】:

我正在尝试创建一个脚本,当激活热键时,它会监听按下的下一个键并在字典中查找它以返回一个值。调试的时候可以正常运行,但是正常运行的时候没有正确响应,我认为是线程处理的问题,但是不知道怎么解决。

import keyboard
import ast
from pynput import keyboard as kb

keyboard_events=
path = 'D:\\shortcuts.ini'
file = open(path, 'r')
content = file.read()
keyboard_events = ast.literal_eval(content)
current = set()

def on_activate():
    print('Global hotkey activated!')
    try:
        c = keyboard.read_key()
    except:
        print()
    if c in keyboard_events:
        print(keyboard_events[c])
        keyboard.write(keyboard_events[c])


def for_canonical(f):
    return lambda k: f(l.canonical(k))

hotkey = kb.HotKey(
    kb.HotKey.parse('<ctrl>+<shift>'),
    on_activate)
with kb.Listener(
        on_press=for_canonical(hotkey.press),
        on_release=for_canonical(hotkey.release)) as l:
    l.join()

【问题讨论】:

【参考方案1】:

已解决,问题不是线程,而是使用热键,键被“按下”。我分享解决方案 '''

import keyboard
import ast
from pynput import keyboard as kb
import time

keyboard_events=
path = 'shortcuts.ini'
file = open(path, 'r')
content = file.read()
keyboard_events = ast.literal_eval(content)
current = set()

def on_activate():
    time.sleep(0.1)
    keyboard.press_and_release('ctrl')
    keyboard.press_and_release('shift')
    time.sleep(0.1)
    c = keyboard.read_key()

    if c == 'ctrl' or 'mayusculas':
        c = keyboard.read_key()

    if c in keyboard_events:
        keyboard.press('backspace')
        keyboard.write(keyboard_events[c])


def for_canonical(f):
    return lambda k: f(l.canonical(k))

hotkey = kb.HotKey(
    kb.HotKey.parse('<ctrl>+<shift>'),
    on_activate)
with kb.Listener(
        on_press=for_canonical(hotkey.press),
        on_release=for_canonical(hotkey.release)) as l:
    l.join()

'''

【讨论】:

以上是关于使用 pynput 监听器创建键盘快捷键的主要内容,如果未能解决你的问题,请参考以下文章

如何通过pynput与日志记录实现键盘鼠标的监听行为?

python pynput鼠标键盘监控(详细)第2部键盘监控tcy

如何监听windows虚拟键盘

android 横屏状态,如何监听键盘的弹起与隐藏

Android 手机软键盘的弹起和关闭的监听

使用 pynput 键盘检测小键盘键