Introduction to Win32
The Win32 API is the core set of application programming interfaces available in Windows operating systems. Despite its age, it remains the foundation for Windows desktop development and provides unmatched control and performance.
Why Learn Win32?
- Maximum Performance: Direct access to system resources
- Complete Control: Fine-grained manipulation of windows and messages
- Foundation: All other Windows frameworks build upon Win32
- Legacy Support: Maintain and extend existing applications
Your First Win32 Application
#include <windows.h>
// Window procedure
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
TextOut(hdc, 50, 50, TEXT("Hello, Win32!"), 13);
EndPaint(hwnd, &ps);
return 0;
}
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow) {
// Register window class
WNDCLASS wc = {};
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.lpszClassName = TEXT("MyWindowClass");
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
RegisterClass(&wc);
// Create window
HWND hwnd = CreateWindowEx(
0, TEXT("MyWindowClass"), TEXT("My First Win32 App"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 800, 600,
NULL, NULL, hInstance, NULL
);
ShowWindow(hwnd, nCmdShow);
// Message loop
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
Key Concepts
Message Loop
Windows applications are event-driven. The message loop retrieves messages from the queue and dispatches them to window procedures.
Window Procedure
Each window class has a procedure that handles messages (WM_PAINT, WM_DESTROY, etc.).
Common Messages
- WM_CREATE: Window is being created
- WM_PAINT: Window needs repainting
- WM_SIZE: Window size changed
- WM_COMMAND: Menu or button clicked
- WM_DESTROY: Window is being destroyed
Modern Win32
Modern Windows development combines Win32 with newer technologies:
- Direct2D and DirectWrite for hardware-accelerated 2D graphics
- Windows Runtime (WinRT) for modern APIs
- XAML Islands for modern UI in Win32 apps