GetAsyncKeyState(i) == -32767 meaning ?

I want to know meant by GetAsyncKeyState(i)==-32767.
This is a part of a simple key logger code.

1
2
3
4
5
6
   for(i = 8; i <= 190; i++)
        {
if (GetAsyncKeyState(i) == -32767)
SaveLogs (i,"MYLOGS.txt");    // This will send the value of 'i' and "MYLOGS.txt" to our SaveLogs function.
        }
It means the code was written by someone who doesn't fully understand how to use GetAsyncKeyState.


GetAsyncKeyState will give you two keystates in two different bits:

bit 15 - the key's real-time state is that it is being held down
bit 0 - the key has just been pressed, so it has just transitioned from released->pressed


The value -32767 is equal to 0x8001 for a signed 16-bit value. Therefore, GetAsyncKeyState(i) == -32767) checks for 3 things:

1) the key is currently being held down
2) the key has just transitioned from released->pressed
3) all other bits in GetAsyncKeyState are zero (which may or may not always be true)



A better way to do this would be to isolate the 1 bit you are interested in. In this case... you'd be interested in bit 0:

1
2
3
4
if( GetAsyncKeyState(i) & 0x0001 )  // <- much better
{
    //...
}
Last edited on
If the most significant bit is set, the key is down
http://msdn.microsoft.com/en-us/library/windows/desktop/ms646293(v=vs.85).aspx
and also the least significant bit (bit 0)... which is actually what OP's code seems to be interested in:

That MSDN page wrote:

if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState. However, you should not rely on this last behavior; for more information, see the Remarks.

...

Although the least significant bit of the return value indicates whether the key has been pressed since the last query, due to the pre-emptive multitasking nature of Windows, another application can call GetAsyncKeyState and receive the "recently pressed" bit instead of your application. The behavior of the least significant bit of the return value is retained strictly for compatibility with 16-bit Windows applications (which are non-preemptive) and should not be relied upon.
Thnx 4 Dish & AbstractionAnion.
Actually I want to detect key pressed. Is it possible with GetAsyncKeyState() ? or any other suggestions regarding that...
Topic archived. No new replies allowed.