求助 Python 监听大写锁定键

2020-07-09 06:52:39 +08:00
 JackalZhao

需求:

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

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

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

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

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

给 LZ 两个关键词
SetWindowsHookEx

WH_KEYBOARD_LL

自己搜去吧
JackalZhao
2020-07-09 10:46:03 +08:00
用 keyboard 和 thread 解决了。
mutalisk
2020-07-09 12:24:39 +08:00
pyhook
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
2020-07-09 14:13:30 +08:00
@ysc3839 原来如此,这两是例外啊。一直都是搞个 dll 写的。。。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/688403

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX