Processing Keyboard Hardware Input
Introduction
Welcome back to System Events and Integration. We are now in Lesson 3, so we already know how to react to timer events and mouse input; now, we are adding another major part of event-driven programming: the keyboard.
In this lesson, we will process hardware key input by handling WM_KEYDOWN. Our goal is simple and useful: when the user presses Esc, the window will treat it like a shortcut, show a confirmation dialog, and close only if the user agrees. This gives us a clean first example of turning a raw key press into real application logic.
From Characters To Hardware Keys
As you may recall from previous units, WinAPI messages carry different kinds of data depending on the event. Mouse clicks gave us coordinates through lParam. Keyboard key presses work differently: WM_KEYDOWN places the important value in wParam.
Here is the key idea:
WM_KEYDOWNtells us that a key was pressed.wParamcontains a virtual key code, such asVK_ESCAPEorVK_F1.- Virtual key codes are great for shortcuts because they describe the logical key, not typed text.
It is important to note that keyboard messages are sent only to the window that currently has input focus. If the user clicks away to another application, your window will stop receiving these messages. This ensures that only the active window processes the user's typing.
That is why this message is a better fit for keys like Esc, arrows, and function keys than character-based input.
Painting A Visible Prompt
Before we react to the keyboard, it helps to show a clear instruction in the window. We do that in WM_PAINT, which is the proper place for drawing. This keeps the visual part of the program separate from the input part, a pattern that should feel familiar after the mouse lesson.
This code starts a paint cycle with BeginPaint, draws a wide string with TextOutW, then ends the cycle with EndPaint. Using lstrlenW(msg) means we let WinAPI compute the string length for us instead of hardcoding it. The result is a small prompt inside the client area:
