简体   繁体   中英

Check if key is pressed on background using win32api

I'm trying to make a simple Python script to capture image from my webcam on workstation unlock. And I am making a "kill switch" that checks if key is pressed and if it does the program will not run. My problem is that I need to check if key is pressed and I can't find a way to do that. I have tried this:

 keyState = win32api.GetAsyncKeyState(17)

But it does not work.

From the documentation:

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

So it doesn't really help me. I'm on Windows btw.

First, GetAsyncKeyState() Also need to AND(&) 0x8000 to ensure the key is down.

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.

Note that the return value is bit-encoded (not a boolean). You should clear the the least significant bit like:

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

And, there is a simple solution without window focus in python. You could get the it through pynput .

Command line:

> pip install pynput

Python code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM