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:
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
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 visibleUpdateWindow(hwnd); // Force initial WM_PAINTWindow Styles
// Basic styles (combined with |):WS_OVERLAPPED // Title bar + borderWS_CAPTION // Title barWS_SYSMENU // System menu (close button)WS_THICKFRAME // Resizable borderWS_MINIMIZEBOX // Minimise buttonWS_MAXIMIZEBOX // Maximise buttonWS_OVERLAPPEDWINDOW // All of the above combined
WS_POPUP // Popup window (no title bar)WS_CHILD // Child window (inside parent)WS_VISIBLE // Initially visibleWS_DISABLED // Initially disabled
// Extended styles (first parameter of CreateWindowEx):WS_EX_TOPMOST // Always on topWS_EX_TOOLWINDOW // Tool window (small title, no taskbar)WS_EX_TRANSPARENT // Click-through transparentWS_EX_LAYERED // Layered window (alpha blending)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:
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 PostQuitMessageHow It Works
1. User presses a key or moves the mouse2. Kernel input subsystem (win32k.sys) creates a message3. Message is placed in the thread's message queue4. GetMessage() retrieves the message (blocks if queue empty)5. TranslateMessage() generates WM_CHAR from WM_KEYDOWN6. DispatchMessage() calls the WndProc for the target window7. WndProc processes the message and returns8. Loop continues until GetMessage returns 0 (WM_QUIT received)GetMessage vs PeekMessage
// GetMessage: blocks until a message is available// Returns 0 only for WM_QUIT, -1 on errorwhile (GetMessage(&msg, NULL, 0, 0)) { ... }
// PeekMessage: non-blocking, returns immediately// Used for game loops that need continuous processingwhile (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:
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
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 repaintingWM_SIZE - Window was resizedWM_MOVE - Window was movedWM_COMMAND - Menu item selected or control notificationWM_KEYDOWN - Key pressed (virtual key code)WM_KEYUP - Key releasedWM_CHAR - Character input (after TranslateMessage)WM_MOUSEMOVE - Mouse movedWM_LBUTTONDOWN/UP - Left mouse buttonWM_RBUTTONDOWN/UP - Right mouse buttonWM_MOUSEWHEEL - Mouse wheel scrolledWM_TIMER - Timer elapsedWM_ERASEBKGND - Erase background before paintWM_SETFOCUS - Window gained keyboard focusWM_KILLFOCUS - Window lost keyboard focusMessages 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:
// Mark a region as needing repaintRECT 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
// 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 timerKillTimer(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.