Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using GetKeyState()

I would like to have a boolean event toggle when a key is pressed. Specifically, the 's' key. I have been pointed to the function GetKeyState(), which supposedly works under the Win32 API. I understand the ASCII code for the letter 's' is 115, and so my code is as follows:

if (GetKeyState(115) == 1)
{
<EVENT>
}

However, this does not work. Why? Here is the MSDN reference: http://msdn.microsoft.com/en-us/library/ms646301%28v=vs.85%29.aspx ... "If the low-order bit is 1, the key is toggled"

like image 442
CaptainProg Avatar asked Jun 13 '11 14:06

CaptainProg


2 Answers

From what I understand you need to do:

if( GetKeyState(115) & 0x8000 )
{
    <EVENT>
}

The highest bit tells if key is pressed. The lowest tells if key is toggled (like, if caps lock is turned on).

like image 168
Piotr Praszmo Avatar answered Sep 24 '22 18:09

Piotr Praszmo


Since SHORT is signed, high-order bit equals sign bit.

Therefore to test if a given key is pressed, simply test if the value returned by GetKeyState() is negative:

if (GetKeyState('S') < 0) {
    // The S key is down.
} else {
    // The S key is up.
}

Besides, 115 is ASCII code for 's'. I believe, you should use capital case 83 to test the 'S' key.

like image 27
Simon Rozman Avatar answered Sep 23 '22 18:09

Simon Rozman