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

Check if key is pressed on background using win32api

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

 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.

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

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

并且,在 python 中有一个没有 window 焦点的简单解决方案。你可以通过 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