Overview
The Windows UI event model provides a set of messages that are sent to window procedures (WndProc) when a user interacts with the graphical interface. These messages are the cornerstone of handling input, system notifications, and control-specific actions in native Win32 applications.
Common Events
| Message | Description | Macro |
|---|---|---|
| WM_CREATE | Sent when a window is being created. | WM_CREATE |
| WM_DESTROY | Sent when a window is being destroyed. | WM_DESTROY |
| WM_PAINT | Request to repaint the client area. | WM_PAINT |
| WM_CLOSE | Sent when a window is about to close. | WM_CLOSE |
| WM_QUIT | Posted to exit the message loop. | WM_QUIT |
Keyboard Events
| Message | Description |
|---|---|
| WM_KEYDOWN | Key pressed (repeatable). |
| WM_KEYUP | Key released. |
| WM_CHAR | Character generated by a key press. |
| WM_SYSKEYDOWN | System key pressed (e.g., ALT). |
| WM_SYSKEYUP | System key released. |
Mouse Events
| Message | Description |
|---|---|
| WM_LBUTTONDOWN | Left mouse button pressed. |
| WM_LBUTTONUP | Left mouse button released. |
| WM_RBUTTONDOWN | Right mouse button pressed. |
| WM_RBUTTONUP | Right mouse button released. |
| WM_MOUSEMOVE | Mouse cursor moved. |
| WM_MOUSEWHEEL | Mouse wheel rotated. |
Usage Example
The following minimal Win32 program demonstrates handling of basic UI events such as creation, painting, keyboard input, and mouse clicks.
// SimpleWinEvents.cpp
#include <windows.h>
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CREATE:
SetWindowText(hwnd, L"UI Events Demo");
return 0;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
TextOutW(hdc, 10, 10, L"Press any key or click the mouse.", 30);
EndPaint(hwnd, &ps);
}
return 0;
case WM_KEYDOWN:
MessageBoxW(hwnd, L"Key pressed!", L"Keyboard", MB_OK);
return 0;
case WM_LBUTTONDOWN:
MessageBoxW(hwnd, L"Left mouse button clicked!", L"Mouse", MB_OK);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProcW(hwnd, msg, wParam, lParam);
}
int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, PWSTR, int nCmdShow)
{
const wchar_t CLASS_NAME[] = L"DemoWindowClass";
WNDCLASSW wc = { };
wc.lpfnWndProc = WndProc;
wc.hInstance = hInst;
wc.lpszClassName = CLASS_NAME;
wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
RegisterClassW(&wc);
HWND hwnd = CreateWindowExW(
0, CLASS_NAME, L"UI Events Demo",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 500, 300,
nullptr, nullptr, hInst, nullptr);
if (hwnd == nullptr) return 0;
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
MSG msg;
while (GetMessageW(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
return (int)msg.wParam;
}
Compile with:
cl /EHsc SimpleWinEvents.cpp user32.lib gdi32.lib