What’s the difference between GetKeyState and GetAsyncKeyState?

Date:November 30, 2004 / year-entry #406
Tags:code
Orig Link:https://blogs.msdn.microsoft.com/oldnewthing/20041130-00/?p=37173
Comments:    14
Summary:I've seen some confusion over the difference between the GetKeyState function and the GetAsyncKeyState function. GetKeyState returns the virtual key state. In other words, GetKeyState reports the state of the keyboard based on the messages you have retrieved from your input queue. This is not the same as the physical keyboard state: If the user...

I've seen some confusion over the difference between the GetKeyState function and the GetAsyncKeyState function.

GetKeyState returns the virtual key state. In other words, GetKeyState reports the state of the keyboard based on the messages you have retrieved from your input queue. This is not the same as the physical keyboard state:

  • If the user has typed ahead, GetKeyState doesn't report those changes until you use the PeekMessage function or the GetMessage function to retrieve the message from your input queue.

  • If the user has switched to another program, then the GetKeyState function will not see the input that the user typed into that other program, since that input was not sent to your input queue.

When should you use GetKeyState and when should you use GetAsyncKeyState?

For user interface work, you nearly always want GetKeyState.

If you are responding to an input message and want to know what keys were pressed at the time that input was generated, then you want to use GetKeyState. For example, if you want to distinguish a left-click of the mouse from an Alt+LeftClick, you must use GetKeyState to query the state of the Alt key (known as VK_MENU for historical reasons). That's because you want to know whether the Alt key was down when the user clicked the mouse, not whether the key is down this very instant. Whether the user released the Alt key between the time they clicked and the time you processed the message is irrelevant. You care that the Alt key was down at the time of the click.

Note that if you are implementing a context menu handler, then you shouldn't be using either GetKeyState or GetAsyncKeyState, because the context menu can be invoked programmatically without any user action. For IContextMenu::QueryContextMenu, you should test for the CMF_EXTENDEDVERBS flag to detect whether you should display extended commands rather than querying the keyboard directly. Similarly, for IContextMenu::InvokeCommand, you should be testing the CMIC_MASK_CONTROL_DOWN and CMIC_MASK_SHIFT_DOWN flags if you want to alter your behavior based on the shift states.

Given this primer on the difference between GetKeyState and GetAsyncKeyState, you can now explain the behavior this user is seeing.

[Updated: 1 Dec 2004, minor typo.]


Comments (14)
  1. asdf says:

    And similarly, I see a lot of people using GetCursorPos when they really meant GetMessagePos.

  2. Ben Hutchings says:

    …and why on Windows 95, pressing Shift-Delete to bypass the recycle bin doesn’t work if you release Shift too quickly.

  3. GregM says:

    Thanks asdf, I’d never heard of GetMessagePos before.

    It sure would have been nice if the GetCursorPos documentation included a link to GetMessagePos, like GetMessagePos has links to GetCursorPos.

  4. Centaur says:

    I once had a problem with tinysfv, a console CRC32 calculator. In short, it takes names of files on the command line, calculates CRC32 for each and puts them into a crc.sfv file.

    Of course, this is done way longer than said; you typically switch to another program while tinysfv is calculating. Then you switch back to check on the status, only to find that it had aborted for no particular reason.

    When I looked at the source (thankfully, it comes with sources), I found this:

    while (PeekMessage(&message, NULL, 0, 0, PM_REMOVE))

    {

    TranslateMessage(&message); // Translate keyboard messages DispatchMessage(&message); // Message handling

    }

    if (GetAsyncKeyState(VK_ESCAPE) & 0x8001)

    {

    Abort = TRUE;

    return 0;

    }

    Now that was a major WTF to me. A console program, having a message pump, and on top of that, polling for Escape? Whatever happened to good old Ctrl+C? Of course, removing these lines fixed everything.

  5. Matt Green says:

    With regard to context menu handlers, you discuss what to do if you are using IContextMenu, I assume based on the MSDN documentation for it that it is for shell context menus only. I am wondering if there is a correct way to check for keys being held down when implementing context menus in other applications. Right now I am just using GetKeyState().

  6. NealSid says:

    is it because no message is stuck in the input queue when setting numlock programmatically?

  7. Raymond Chen says:

    The numlock message is in the queue. That’s the problem.

  8. splintor says:

    Typo: "When should use use" should be "When should you use"

  9. mschaef says:

    What’s a viable use case for GetAsyncKeyState?

  10. Tim Dawson says:

    Checking for keyboard input in a game loop.

  11. Tom Seddon says:

    Except then you’d want DirectInput :)

  12. bob says:

    I see a good point here!

    bob@abirnet.co.il

  13. DirectInput is overkill.

  14. Tom Seddon says:

    Not for games, I don’t think. It will (optionally) disable the windows key for you — nobody likes a working windows key when playing a game! Definitely worth the effort of using it, I think, though ‘effort’ is hardly the right word since it’s only about 60 lines to set up the keyboard (less if you support 1 version of DirectX and don’t use the emulated versions) and extremely easy to use once it’s running.

Comments are closed.


*DISCLAIMER: I DO NOT OWN THIS CONTENT. If you are the owner and would like it removed, please contact me. The content herein is an archived reproduction of entries from Raymond Chen's "Old New Thing" Blog (most recent link is here). It may have slight formatting modifications for consistency and to improve readability.

WHY DID I DUPLICATE THIS CONTENT HERE? Let me first say this site has never had anything to sell and has never shown ads of any kind. I have nothing monetarily to gain by duplicating content here. Because I had made my own local copy of this content throughout the years, for ease of using tools like grep, I decided to put it online after I discovered some of the original content previously and publicly available, had disappeared approximately early to mid 2019. At the same time, I present the content in an easily accessible theme-agnostic way.

The information provided by Raymond's blog is, for all practical purposes, more authoritative on Windows Development than Microsoft's own MSDN documentation and should be considered supplemental reading to that documentation. The wealth of missing details provided by this blog that Microsoft could not or did not document about Windows over the years is vital enough, many would agree an online "backup" of these details is a necessary endeavor. Specifics include:

<-- Back to Old New Thing Archive Index