Skip to main content
Be Bitwise

Window Classes & Message Loop

Windows API - GUI & System Programming · Windows Programming track

11 min read

In this module

The Windows GUI Programming Model

Win32 GUI code runs on a message bus. Most modern frameworks let you wire up a click handler to a button and forget about the plumbing. Win32 doesn't. Every keystroke, every mouse twitch, every paint request comes through a single function called your window procedure, and that function is going to switch on a 16-bit message code and decide what to do. Once you can read a message loop, you can read every Windows GUI program ever written, debug them when they hang, and understand exactly how user input gets from the keyboard driver to your code.

Registering a Window Class

Before you can create a window, you must register a window class that defines the window's behaviour:

c
WNDCLASSEX wc = {
.cbSize = sizeof(WNDCLASSEX),
.style = CS_HREDRAW | CS_VREDRAW, // Redraw on resize
.lpfnWndProc = WndProc, // Message handler
.cbClsExtra = 0, // Extra class bytes
.cbWndExtra = 0, // Extra window bytes
.hInstance = hInstance, // Module handle
.hIcon = LoadIcon(NULL, IDI_APPLICATION),
.hCursor = LoadCursor(NULL, IDC_ARROW),
.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1), // Background brush
.lpszMenuName = NULL, // Menu resource name
.lpszClassName = TEXT("MyWindowClass"), // Class name
.hIconSm = NULL // Small icon
};
if (!RegisterClassEx(&wc)) {
// Registration failed
return 0;
}

The field that actually matters is lpfnWndProc, a function pointer to the window procedure that handles every message sent to a window of this class. Multiple windows can share a class, which means they share the WndProc — handy when you want fifty buttons to behave identically without registering fifty handlers.

Creating a Window

c
HWND hwnd = CreateWindowEx(
0, // Extended style (WS_EX_TOPMOST, etc.)
TEXT("MyWindowClass"), // Class name (registered above)
TEXT("My Application"), // Window title
WS_OVERLAPPEDWINDOW, // Style flags
CW_USEDEFAULT, // X position
CW_USEDEFAULT, // Y position
800, // Width
600, // Height
NULL, // Parent window
NULL, // Menu handle
hInstance, // Module handle
NULL // Create parameter (passed to WM_CREATE)
);
ShowWindow(hwnd, nCmdShow); // Make window visible
UpdateWindow(hwnd); // Force initial WM_PAINT

Window Styles

c
// Basic styles (combined with |):
WS_OVERLAPPED // Title bar + border
WS_CAPTION // Title bar
WS_SYSMENU // System menu (close button)
WS_THICKFRAME // Resizable border
WS_MINIMIZEBOX // Minimise button
WS_MAXIMIZEBOX // Maximise button
WS_OVERLAPPEDWINDOW // All of the above combined
WS_POPUP // Popup window (no title bar)
WS_CHILD // Child window (inside parent)
WS_VISIBLE // Initially visible
WS_DISABLED // Initially disabled
// Extended styles (first parameter of CreateWindowEx):
WS_EX_TOPMOST // Always on top
WS_EX_TOOLWINDOW // Tool window (small title, no taskbar)
WS_EX_TRANSPARENT // Click-through transparent
WS_EX_LAYERED // Layered window (alpha blending)
Window Hierarchy

Windows are organised in a hierarchy. A parent window can have child windows (with WS_CHILD style). Child windows are clipped to their parent's client area and move with the parent. Top-level windows (without WS_CHILD) can have owner-owned relationships - an owned window is always above its owner and is hidden/destroyed with its owner. This hierarchy determines z-order, input routing, and lifetime management.

The Message Loop

The message loop is the heart of every GUI application:

c
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg); // Convert key messages to char messages
DispatchMessage(&msg); // Send to window procedure
}
return (int)msg.wParam; // Exit code from PostQuitMessage

How It Works

text
1. User presses a key or moves the mouse
2. Kernel input subsystem (win32k.sys) creates a message
3. Message is placed in the thread's message queue
4. GetMessage() retrieves the message (blocks if queue empty)
5. TranslateMessage() generates WM_CHAR from WM_KEYDOWN
6. DispatchMessage() calls the WndProc for the target window
7. WndProc processes the message and returns
8. Loop continues until GetMessage returns 0 (WM_QUIT received)

GetMessage vs PeekMessage

c
// GetMessage: blocks until a message is available
// Returns 0 only for WM_QUIT, -1 on error
while (GetMessage(&msg, NULL, 0, 0)) { ... }
// PeekMessage: non-blocking, returns immediately
// Used for game loops that need continuous processing
while (running) {
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
if (msg.message == WM_QUIT) break;
TranslateMessage(&msg);
DispatchMessage(&msg);
} else {
// No messages - do game logic / rendering
UpdateGame();
RenderFrame();
}
}

The Window Procedure (WndProc)

The window procedure is a callback function that processes all messages for a window:

c
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_CREATE: {
// Window is being created
// lParam points to CREATESTRUCT with creation parameters
CREATESTRUCT *cs = (CREATESTRUCT *)lParam;
return 0;
}
case WM_SIZE: {
// Window was resized
int width = LOWORD(lParam);
int height = HIWORD(lParam);
// Resize child controls, update layout...
return 0;
}
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
// ps.rcPaint = the invalid rectangle that needs repainting
// Draw content
TextOut(hdc, 10, 10, TEXT("Hello!"), 6);
Rectangle(hdc, 50, 50, 200, 150);
EndPaint(hwnd, &ps); // Validates the invalid region
return 0;
}
case WM_KEYDOWN: {
// A key was pressed (wParam = virtual key code)
if (wParam == VK_ESCAPE) {
PostMessage(hwnd, WM_CLOSE, 0, 0);
}
return 0;
}
case WM_LBUTTONDOWN: {
// Left mouse button pressed
int x = GET_X_LPARAM(lParam);
int y = GET_Y_LPARAM(lParam);
// Handle click at (x, y)...
return 0;
}
case WM_CLOSE:
// User clicked X button - confirm before destroying
if (MessageBox(hwnd, TEXT("Really quit?"), TEXT("Confirm"),
MB_YESNO) == IDYES) {
DestroyWindow(hwnd);
}
return 0;
case WM_DESTROY:
// Window is being destroyed
PostQuitMessage(0); // Puts WM_QUIT in the message queue
return 0;
}
// Default handling for unprocessed messages
return DefWindowProc(hwnd, msg, wParam, lParam);
}

Key Messages

text
WM_CREATE - Window created (one-time initialisation)
WM_DESTROY - Window being destroyed (cleanup)
WM_CLOSE - User requested close (X button, Alt+F4)
WM_PAINT - Window needs repainting
WM_SIZE - Window was resized
WM_MOVE - Window was moved
WM_COMMAND - Menu item selected or control notification
WM_KEYDOWN - Key pressed (virtual key code)
WM_KEYUP - Key released
WM_CHAR - Character input (after TranslateMessage)
WM_MOUSEMOVE - Mouse moved
WM_LBUTTONDOWN/UP - Left mouse button
WM_RBUTTONDOWN/UP - Right mouse button
WM_MOUSEWHEEL - Mouse wheel scrolled
WM_TIMER - Timer elapsed
WM_ERASEBKGND - Erase background before paint
WM_SETFOCUS - Window gained keyboard focus
WM_KILLFOCUS - Window lost keyboard focus
Key Concept
Sent vs Posted Messages

Messages can be sent (SendMessage) or posted (PostMessage). SendMessage calls the target WndProc directly and blocks until it returns - the message bypasses the queue. PostMessage places the message in the target thread's queue and returns immediately. This distinction matters for thread safety: SendMessage across threads causes the calling thread to wait while the target thread processes the message, which can cause deadlocks if both threads are sending to each other.

Painting and the Invalid Region

Painting is lazy in Win32. You don't draw on demand; you mark regions as invalid, and the system gets back to you with a WM_PAINT when it's good and ready:

c
// Mark a region as needing repaint
RECT rc = { 50, 50, 200, 200 };
InvalidateRect(hwnd, &rc, TRUE);
// TRUE = erase background before repainting
// Windows will send WM_PAINT with this region included
// Force immediate repaint (instead of waiting for message loop)
UpdateWindow(hwnd); // Sends WM_PAINT directly if there's an invalid region
// Inside WM_PAINT:
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
// ps.rcPaint contains the invalid rectangle
// Only draw within this rectangle for efficiency
// Fill background
FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW + 1));
// Draw content
SetTextColor(hdc, RGB(0, 0, 0));
SetBkMode(hdc, TRANSPARENT);
DrawText(hdc, TEXT("Centered Text"), -1, &clientRect,
DT_CENTER | DT_VCENTER | DT_SINGLELINE);
EndPaint(hwnd, &ps); // Validates the region
return 0;
}

The trick is coalescing. Invalidate ten different little rectangles in quick succession and Windows merges them into one WM_PAINT covering their union, so you don't end up redrawing the same pixels ten times.

Timer Messages

c
// Set a recurring timer (fires every 1000ms)
SetTimer(hwnd, TIMER_ID, 1000, NULL);
// NULL callback = sends WM_TIMER to window procedure
case WM_TIMER:
if (wParam == TIMER_ID) {
// Timer fired - update animation, check status, etc.
InvalidateRect(hwnd, NULL, TRUE); // Trigger repaint
}
return 0;
// Remove the timer
KillTimer(hwnd, TIMER_ID);

The message-loop model is the bedrock of Windows GUI programming. Keyboard, mouse, resize, timer — every interaction the user can have with your window crosses that queue and dispatches through your WndProc. WPF, WinUI, .NET MAUI, even WinUI 3: all of them are wrappers. Crack one open and somewhere down the call stack you'll find DispatchMessage doing its thing, exactly as it has since Windows 1.0 in 1985.