Search code examples
c#functionkeylogger

GetAsyncKeyState Explanation required


I wanted to make a little keylogger using the console application and I stumbled across this source code on the web and I have trouble understanding it.

while(true)
{
    Thread.Sleep(10);

    for (int i = 0; i < 255; i++)
    {
        int keyState = GetAsyncKeyState(i);

        if (keyState == -32767)
        {
            Console.WriteLine((Keys)i);
        }
    }
}

So from what I understand, keystate is basically a function which tells if a key is currently being pressed. Since we want to check if any of the 255 keyboard keys are being checked we need a for cycle. Correct me if I am wrong.

So if the key we are currently pressing is well... pressed, it will return some Value (Would like to know what value this is...maybe the keycode value? Correct me because I am sure I am wrong).

But the IF is the part where I have totally lost it. If my understanding is correct, then the write line will only happen if we get -32767 which is who knows what? And that is what I would like to know. Why is it -32767? How come it works even if we never get -32767, LMB is 1 for example...?


Solution

  • If my understanding is correct, then the write line will only happen if we get -32767 which is who knows what?

    The value of -32767 (0x8001) is an important value. GetAsyncKeyState returns a short, which means it is the least significant bit (0) of the 16bit return value.

    According to the docs:

    If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState. That means it is looking for a key press between calls.