How GetKeyState works exactly?

639 views Asked by At

I have been struggling with understand how GetKeyState operating. I have done endless google searching and haven't yet managed yet to understand exactly how it works

According to MSDN:

The key status returned from this function changes as a thread reads key messages from its message queue.

Take a look at the following code. I didn't create a message processing loop. 65 represents the virtual key of the character 'A'.

while(true) {

    printf("the character %c, the vkey_state is %x", 
    MapVirtualKey(65, MAPVK_VK_TO_CHAR),GetKeyState(65) & 0x8000);
    Sleep(150);
}

I pressed "A" on the keyboard, while being at the window console of my program. sometimes, the vkey_state value is 0x8000 as expected, sometimes not.

What exactly is happening under the hood? I didn't write any message-processing code, so i assume it is created automatically. When I press 'A', a WM_KEYDOWN is sent to my thread message queue. When I release the key 'A', a WM_KEYUP is sent to my thread message queue. other key-related messages might be sent in between. What happens when I call GetKeyState? when exactly it will set the MSB of its return value to '1'? When will it change back to 0? Is it related to the calls to GetMessage?

In Addition - what confused me the most - is when I switched to another program (cmd.exe), and I typed 'A', my program was able to monitor it while being in the background - but cmd.exe thread has another message queue - why does it work? However - it didn't work If I started cmd.exe in elevated mode (high integrity).

this contradicts the information I found here.

If the user has switched to another program, then the GetKeyState function will not see the input that the user typed into that other program, since that input was not sent to your input queue.

0

There are 0 answers