How to understand and use the GetKeyState function properly?

燕鹏 李 301 Reputation points
2022-04-20T09:21:36.843+00:00

Hi, a win32 newbie here. I am reading Programming Windows 5ed. But the author has some words in the book that I find very puzzling.

Be careful with GetKeyState. It is not a real-time keyboard status check. Rather, it reflects the keyboard status up to and including the current message being processed.

Does it mean that I have to use this function in WndProc? and this function reflects the key state when processing that message?

Just as you cannot use GetKeyState for a key that has yet to be pressed, you cannot use it for a mouse button that has yet to be pressed. Don’t do this:

while (GetKeyState (VK_LBUTTON) >= 0) ; // WRONG !!!  

The GetKeyState function will report that the left button is depressed only if the button is already depressed when you process the message during which you call GetKeyState.

Why the author said I cannot use this function for a key or mouse button that hasn't been pressed? But using this function to detect if a keyboard or mouse key is pressed is exactly what I want to use it for.

I want to detect mouse or keyboard key presses in the following two cases:

  1. Inside the WndProc. Detect if a mouse button or key is pressed while processing a message.
  2. Outside the WndProc. Detect if a mouse button or key is pressed in a while loop.
Windows development Windows API - Win32
0 comments No comments
{count} votes

Accepted answer
  1. RLWA32 49,536 Reputation points
    2022-04-20T09:32:28.333+00:00

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.