Detecting Key Presses using win32api in Python

27,752

Solution 1

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

Solution 2

This isn't how it works in GUI programming. You don't call a method to check for a key press. Instead you get sent messages when keys are pressed. Assuming that you have a window that is receiving input then you need to respond to the WM_KEYDOWN message arriving in your window procedure, or message map in Python win32api terms.


Your edit shows that you are not using the message queue which is rather unusual. You may be able to achieve what you wish by calling GetAsyncKeyState().

Solution 3

Check the python tiler on github, very useful even if you are trying to just find key codes to send. Also this will be useful if you are running your code in the background and want to break the loop from outside the window.

git project: https://github.com/Tzbob/python-windows-tiler

code with windows keys: https://code.google.com/p/python-windows-tiler/source/browse/pwt/hotkey.py?r=df41af2a42b6304047a5f6f1f2903b601b22eb39

Share:
27,752
rectangletangle
Author by

rectangletangle

Updated on November 13, 2020

Comments

  • rectangletangle
    rectangletangle about 2 years

    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.