python keyboard模块的修改, 解决与autohotkey的冲突问题

在使用keyboard模块设置全局热键时, 发现如果设置为suppress模式, 与autohotkey软件冲突, 导致autohotkey的一些热键不能正常使用, 比如alt+c键. 并且发现keyboard热键不够灵敏, 有时候需要按多次才能够响应.

import keyboard
i = 0
def Temp():
    global i
    i += 1
    print(i)
keyboard.add_hotkey('ctrl+a', Temp,suppress=True)
keyboard.wait()

如上例, 如果autohotkey软件注册了快捷键alt+c, 运行时会出现不能正常工作的情况.
经过阅读keyboard源码, 发现注释掉下面的代码, 就可以解决此问题.
文件: _winkeyboard.py , 相关代码:

    def low_level_keyboard_handler(nCode, wParam, lParam):
        try:
            vk = lParam.contents.vk_code
            # Ignore the second `alt` DOWN observed in some cases. 在某些情况下,忽略观察到的第二个alt按键按下事件。
            #fake_alt = (LLKHF_INJECTED | 0x20)
            # Ignore events generated by SendInput with Unicode. 忽略由SendInput生成的带有Unicode的事件。
            #if vk != VK_PACKET and lParam.contents.flags & fake_alt != fake_alt:
            if vk != VK_PACKET:
                event_type = KEY_UP if wParam & 0x01 else KEY_DOWN
                is_extended = lParam.contents.flags & 1
                scan_code = lParam.contents.scan_code
                should_continue = process_key(event_type, vk, scan_code, is_extended)
                if not should_continue:
                    return -1
        except Exception as e:
            print('Error in keyboard hook:')
            traceback.print_exc()

        return CallNextHookEx(None, nCode, wParam, lParam)

上面被注释掉的那几行就是问题所在. 这样修改之后, 暂时没有发现别的问题.

posted @ 2023-08-26 22:40  顺其自然,道法自然  阅读(208)  评论(0编辑  收藏  举报