gpt4 book ai didi

python - 使用 win32api 检查是否在后台按下了按键

转载 作者:太空宇宙 更新时间:2023-11-03 21:03:32 24 4
gpt4 key购买 nike

我正在尝试制作一个简单的 Python 脚本来在工作站解锁时从网络摄像头捕获图像。我正在制作一个“终止开关”来检查是否按下了键,如果按下了程序将不会运行。我的问题是我需要检查是否按下了键,但我找不到方法来做到这一点。我已经尝试过:

 keyState = win32api.GetAsyncKeyState(17)

但是它不起作用。

来自文档:

The return value is zero if a window in another thread or process currently has the keyboard focus.

所以这对我来说并没有什么帮助。顺便说一句,我使用的是 Windows。

最佳答案

首先,GetAsyncKeyState()还需要AND(&) 0x8000以确保按键按下。

Return Value

Type: SHORT

If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState.

请注意,返回值是位编码的(不是 bool 值)。您应该清除最低有效位,例如:

keyState = win32api.GetAsyncKeyState(17)&0x8000.

而且,Python 中有一个没有窗口焦点的简单解决方案。您可以通过 pynput 获取.

命令行:

> pip install pynput

Python 代码:

from pynput import keyboard

def on_press(key):
try: k = key.char # single-char keys
except: k = key.name # other keys
if key == *(which you want to set):#To Do.

lis = keyboard.Listener(on_press=on_press)
lis.start() # start to listen on a separate thread
lis.join() # no this if main thread is polling self.keys

关于python - 使用 win32api 检查是否在后台按下了按键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55568850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com