You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pynput的GlobalHotkeys中获取按下按键以过滤组合键?

在pynput的GlobalHotKeys中获取按键并过滤组合键

核心思路

GlobalHotKeys支持通过intercept(macOS可使用darwin_intercept)参数传入拦截函数,该函数能捕获每一次按键的按下/释放事件,解析事件对象即可获取按键信息。拦截函数返回True会阻止热键触发,返回False则允许触发,以此实现组合键过滤;同时可通过类属性记录按键状态,在回调函数中直接访问。

修改后的代码实现

MyHotkeys.py

from pynput.keyboard import GlobalHotKeys, Key, KeyCode

class MyHotkeys(GlobalHotKeys):
    def __init__(self, hotkeys):
        # 通用系统用intercept参数,macOS可替换为darwin_intercept
        super().__init__(hotkeys, intercept=self.my_filter)
        self.current_pressed = set()  # 记录当前处于按下状态的按键

    def my_filter(self, event_type, event):
        # 解析按键对象,格式与Listener中的key完全一致
        try:
            key = event.key if isinstance(event, Key) else event
        except AttributeError:
            key = event

        if event_type == 'press':
            self.current_pressed.add(key)
            # 示例:仅当同时按下ctrl+i时,才允许触发热键
            required_keys = {Key.ctrl, KeyCode.from_char('i')}
            if not required_keys.issubset(self.current_pressed):
                return True  # 拦截不符合条件的组合键
        else:
            # 按键释放时从集合中移除
            if key in self.current_pressed:
                self.current_pressed.remove(key)
        
        return False  # 允许触发热键

main.py

from MyHotkeys import MyHotkeys

def my_func():
    print("hello world")
    # 直接从实例属性获取当前按下的按键集合
    print("当前按下的按键:", my_hotkeys.current_pressed)

my_hotkeys = MyHotkeys({"<ctrl>+i": my_func})
my_hotkeys.start()

# 保持程序运行,按下Ctrl+C终止
try:
    while True:
        input()
except KeyboardInterrupt:
    my_hotkeys.stop()

关键说明

  1. 拦截函数参数解析:event_type取值为'press'或'release',event是按键事件对象,可通过isinstance区分特殊键(Key类)和普通字符键(KeyCode类),解析逻辑与Listener完全相同。
  2. 组合键过滤逻辑:利用集合的issubset方法,判断当前按下的按键是否包含所需组合,不符合则拦截热键触发。
  3. 回调函数获取按键:通过自定义类的current_pressed属性,在回调函数中直接访问当前按下的按键状态。

内容的提问来源于stack exchange,提问作者Evaine LeBlanc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 03:35:27