Detecting Key Presses using win32api in Python

win32api is just an interface to the underlying windows low-level library.
See the GetAsyncKeyState Function:

Determines whether a key is up or down at the time the function is called, and whether the key was pressed after a previous call to GetAsyncKeyState.

Syntax

SHORT WINAPI GetAsyncKeyState(
__in  int vKey
);

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).
To get at vKey values, an application can use the virtual-key code constants in the win32con module.

For example, testing the “CAPS LOCK” key:

>>> import win32api
>>> import win32con
>>> win32con.VK_CAPITAL
20
>>> win32api.GetAsyncKeyState(win32con.VK_CAPITAL)
0
>>> win32api.GetAsyncKeyState(win32con.VK_CAPITAL)
1

The virtual-key constant for simple letters are ASCII codes,
so that testing the state of the “H” key (key was pressed) will look like:

>>> win32api.GetAsyncKeyState(ord('H'))
1

Leave a Comment