Search code examples
pythonwinapikey-bindings

Detecting Key Presses using win32api in Python


I'm trying to break a loop in Python with a specific key press using win32api. How would one go about this?

What is the actual version of win32api.KeyPress('H'), in the following code?

Revised:

import win32api

while True :
    cp = win32api.GetCursorPos()
    print cp
    if win32api.KeyPress('H') == True :
        break

I want to be able to break a loop by pressing the h key.

Edit:

I'm attempting to make a program that repeatedly reports mouse positions and I need a mechanism to exit said program.

See revised code.


Solution

  • 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