V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
JackalZhao
V2EX  ›  问与答

求助 Python 监听大写锁定键

  •  
  •   JackalZhao · 2020-07-09 06:52:39 +08:00 · 1609 次点击
    这是一个创建于 1377 天前的主题,其中的信息可能已经有所发展或是发生改变。

    需求:

    持续监听大写锁定键,当按下后,保持按下状态超过 0.5 秒时,立即 print('超过 0.5 秒')

    (一旦在持续 0.5 秒之前松开了,那就啥都不做)

    当按下超过 0.5 秒后,松开这个按键时,print('松开了')。

    尽可能简洁、占用资源尽可能少。

    10 条回复    2020-07-09 14:13:30 +08:00
    singerll
        1
    singerll  
       2020-07-09 07:04:31 +08:00 via Android
    先报价
    loading
        2
    loading  
       2020-07-09 07:38:24 +08:00 via Android
    caps lck 键有按下释放事件吗?容我有空的时候去看看。
    manning
        3
    manning  
       2020-07-09 09:38:45 +08:00
    keyboard hook windows api
    hakono
        4
    hakono  
       2020-07-09 09:51:32 +08:00 via Android
    这不是 Python 编程知识,而是 win32 开发知识,请用 c 或 c++来写
    这里涉及到 Windows 的全局 hook 相关的 api 以及 Windows 的消息事件
    这个基础需要去学一下的
    https://zhuanlan.zhihu.com/p/31962703
    以及,全局 hook 必须需要你编译一个 dll 用来注入,这就是为什么让你用 c 或 c++来写,了解之后实现这个功能非常简单几十行代码就行了
    rming
        5
    rming  
       2020-07-09 10:03:12 +08:00 via iPhone
    推荐 2 个库 pynput keyboard
    tabris17
        6
    tabris17  
       2020-07-09 10:11:25 +08:00
    用底层键盘消息钩子就可以了

    给 LZ 两个关键词
    SetWindowsHookEx

    WH_KEYBOARD_LL

    自己搜去吧
    JackalZhao
        7
    JackalZhao  
    OP
       2020-07-09 10:46:03 +08:00 via Android
    用 keyboard 和 thread 解决了。
    mutalisk
        8
    mutalisk  
       2020-07-09 12:24:39 +08:00
    pyhook
    ysc3839
        9
    ysc3839  
       2020-07-09 12:50:46 +08:00
    @hakono “全局 hook 必须需要你编译一个 dll 用来注入”是错的。比如 WH_KEYBOARD_LL 和 WH_MOUSE_LL 是全局的但不需要,微软文档里有写:
    https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms644985(v=vs.85)
    However, the WH_KEYBOARD_LL hook is not injected into another process. Instead, the context switches back to the process that installed the hook and it is called in its original context.

    The Old New Thing 里面也有一篇文章提到了这个:
    https://devblogs.microsoft.com/oldnewthing/20050425-41/?p=35803
    The WH_KEYBOARD_LL and WH_MOUSE_LL hooks are exceptions to this rule. These two are non-injecting hooks, as explained in their respective documentation pages. Rather, the hook function is called in its original thread context.
    hakono
        10
    hakono  
       2020-07-09 14:13:30 +08:00
    @ysc3839 原来如此,这两是例外啊。一直都是搞个 dll 写的。。。。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1266 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 17:57 · PVG 01:57 · LAX 10:57 · JFK 13:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.