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

2024-07-05 15:37:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个简单的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上


Tags: 文件the方法图像程序网络脚本按键
1条回答
网友
1楼 · 发布于 2024-07-05 15:37:39

首先,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.

请注意,返回的位不是布尔值。您应该清除最不重要的部分,如:

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

而且,在python中有一个没有窗口焦点的简单解决方案。你可以通过pynput得到它。在

命令行:

^{pr2}$

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

相关问题 更多 >