VB:Tutorials:WINAPI:GetKeyState API

From GPWiki

Files:GUITutorial_warn.gif The Game Programming Wiki has moved! Files:GUITutorial_warn.gif

The wiki is now hosted by GameDev.NET at wiki.gamedev.net. All gpwiki.org content has been moved to the new server.

However, the GPWiki forums are still active! Come say hello.

"Even a perfect program still has bugs."

In order for a game to function, there must be a user, and that user must be able to input his will into the game. He or she will do this by using usually a combination of mouse and keyboard and maybe other devices. This text will show you how to check for keypresses using a Windows API call called:

Private Declare Function GetKeyState Lib "user32" Alias "GetKeyState" (ByVal nVirtKey As Long) As Integer
          
   'You'll also need these
   Private Const KEY_TOGGLED As Integer = &H1
   Private Const KEY_PRESSED As Integer = &H1000

The way to use this API to test for keypresses is like so:

If GetKeyState(vbKeyUp) And KEY_PRESSED Then _ 
        'the key was pressed
   if GetKeyState(vbkeyCapital) and KEY_TOGGLED Then _
        'Caps lock is ON 

Notice that the toggled flag is used for keys that can have a state, like Numlock etc..

--IGTHORN

Thanks to Andy for giving me the Key_* constant values.