[C++] GetKeyState() incorrectly says numpad key is pressed

Curry 1 Reputation point
2022-05-31T14:49:46.83+00:00

If you hold a Numpad key(s) (e.g. numpad7), then press num lock, then release the Numpad key (numpad7), GetKeyState() and GetAsyncKeyState() both say that the key(s) (numpad7) is still pressed.

Seems like a key-up event is never sent to windows, so it thinks it is still pressed, but..... the key is not artificially held down in text inputs (renaming files, notepad, google search), and works as expected.

For context, I am making a small interactive app that reacts to a user's keypresses (animates someone typing). On the off chance someone presses a Numpad key and num lock at the same time, my app breaks (plays the wrong animation, as it thinks a key (or keys) are still pressed).

My question is: how do I stop or circumvent this behavior?

A simple demo:

#include <windows.h>
#include <winuser.h>

    while (true)
    {
        for (int keycode = 8; keycode <= 222; keycode ++) {
            if (GetAsyncKeyState(keycode ) & 0x8000)
            {
                cout << keycode << " ";
            }
        }
        cout << endl;
    }

The output would be something like:

36 //numpad7 held, with numlock ON
36 144 //numpad7 still held, numlock now tapped (toggled to OFF)
36 //numpad7 released, but it says it held (this shouldn't be possible as numlock is OFF, should be the keycode for home or something, if that physical key was pressed)
36 //still says it's pressed
36 //...

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,413 questions
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,523 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Xiaopo Yang - MSFT 11,336 Reputation points Microsoft Vendor
    2022-06-01T01:57:13.17+00:00

    Hello,

    Welcome to Microsoft Q&A!

    The behavior is only reproduced through VK_NUMLOCK and VK_NUMPADX. It‘s definite that the behavior is caused by VK_NUMLOCK function.
    And for applications, the input is not relied on Get[Async]KeyState rather than such as WM_CHAR, WM_INPUT, etc.

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.