top of page

Testing the state of a key using the GetKeyState Windows API Function

  • Writer: John
    John
  • 3 days ago
  • 2 min read
This post is one of a series providing implementation examples of Windows API Functions, Types, Enums and Consts using VBA. The code in this post can be used as-is, however, if you regularly (or even just occasionally) work with Windows API declarations in VBA, you may want to see the posts Automatically add Windows API declaration(s) and Using 'F1' to view Windows API web pages which explain some of the functionality that can be added to the VBE by VBE_Extras.

This post demonstrates how to use the GetKeyState Windows API Function to test the state of specific keys ... in this case, the Shift, Ctrl, Alt, Caps Lock and Num Lock keys.


GetKeyState is not a complex Function ... you pass it a virtual key code (or an ASCII numeric value if the key is for a letter or digit) and get back a numeric value indicating if the key is currently pressed-down or not and if the key is toggled or not.


The virtual key codes are listed here though VBE_Extras will add Consts for these values to your code.


The returned numeric value has to be handled correctly to get the useful information from it ... as the documentation says: if the high-order bit is 1, the key is down, otherwise, it is up; if the low-order bit is 1, the key is toggled.


The example code also uses the Sleep Windows API Function ... to read more about that, see my Pause processing post.


So here's an implementation example ... actually 2 ... this one demonstrating how to test if a key is currently pressed down, in this case the Shift, Ctrl and Alt keys ...

... and this example demonstrates how to test if a key is toggled, in this case the Caps Lock and Num Lock keys ...


bottom of page