wenxibo
wenxibo

Reputation: 181

What is the difference about GetKeyState and GetAsyncKeyState?

From MSDN , I have learned that GetKeyState is associated with message queue of current thread.

Then I created two sample applications : KeyPresser and BackChecker.

I press a key in KeyPresser , in this application , I am using GetKeyState/GetAsyncKeyState/GetKeyboardState to retrieve the pressed key state , and they tell me that key is pressing down.

Then I send(or post) a message form KeyPresser to BackChecker , to notify BackChecker to check the key state in it's thread .

I get same result from BackChecker indicate that key is pressed. But I think GetKeyState/GetKeyboardState should return zero because the key is pressed in thread of KeyPresser , which is not associated with thread of BackChecker.

Why?

Upvotes: 3

Views: 3159

Answers (1)

Hans Passant
Hans Passant

Reputation: 941873

Keyboard input on Windows is buffered. It ensures the user can keep typing, even if the program is temporarily unresponsive. It always is, to some degree, no loss of keystrokes that way. They are added to the message queue, the program's message loop retrieves them with GetMessage() later.

Along with the keystroke, it also stores the state of all the other keys. To ensure that, when the message is eventually retrieved, you can reliable tell what other keys were down. Very important for the modifier keys for example. A shortcut keystroke like Ctrl+A would not work reliably otherwise.

So you generally always use GetKeyState(), you get the state of the keys as they were recorded originally. Or GetKeyboardState(), you get the whole enchilada. Using GetAsyncKeyState() is much less common, it doesn't rely on the buffered state, only needed if the app has very unusual message handling. Might be appropriate in a game perhaps.

Upvotes: 5

Related Questions