Introduction to the Win32 API
The Windows API (Win32) Fundamentals · Windows Programming track
10 min read
In this module
The Foundation of Windows Programming
The Win32 API is the native programming interface for Windows. Every Windows application — Notepad, Chrome, AAA games — ultimately calls Win32 to talk to the OS. Most modern applications abstract it away with .NET, Qt, or Electron, but the underlying API is what you need to understand for systems programming, security research, driver development, or anything performance-critical.
WinMain: The Windows Entry Point
Unlike console applications that start at main(), graphical Windows applications start at WinMain():
#include <windows.h>
int WINAPI WinMain( HINSTANCE hInstance, // Handle to this module (the EXE) HINSTANCE hPrevInstance, // Always NULL (legacy from Win16) LPSTR lpCmdLine, // Command line arguments (ANSI) int nCmdShow // How to show the window (SW_SHOW, etc.)) { MessageBox(NULL, "Hello, Win32!", "My First App", MB_OK); return 0;}The WINAPI macro expands to __stdcall, the calling convention used by the Win32 API. On 32-bit Windows, stdcall means:
- Arguments are pushed onto the stack right-to-left
- The callee (the called function) cleans up the stack
- This differs from
__cdecl(the C default) where the caller cleans the stack
On 64-bit Windows, there is only one calling convention (the Microsoft x64 convention), so WINAPI is effectively ignored.
An HINSTANCE is a handle to a module (an EXE or DLL loaded into memory). For the main executable, it represents the base address where the PE image is loaded. WinMain receives the HINSTANCE so the application can load resources (icons, dialogs, strings) embedded in its own executable. The hPrevInstance parameter is always NULL - it was used in 16-bit Windows to detect if another instance was already running.
Windows Data Types
The Win32 API defines many custom data types. These are all typedefs for standard C types but provide semantic meaning:
// Integer typestypedef unsigned long DWORD; // 32-bit unsigned (Double WORD)typedef unsigned short WORD; // 16-bit unsignedtypedef unsigned char BYTE; // 8-bit unsignedtypedef int BOOL; // 32-bit boolean (TRUE/FALSE)typedef long LONG; // 32-bit signedtypedef unsigned long ULONG; // 32-bit unsignedtypedef __int64 LONGLONG; // 64-bit signedtypedef unsigned __int64 ULONGLONG; // 64-bit unsigned
// Pointer typestypedef void *PVOID; // Generic pointertypedef void *LPVOID; // "Long pointer" to void (LP = far pointer, legacy)typedef DWORD *LPDWORD; // Pointer to DWORDtypedef const char *LPCSTR; // Pointer to const ANSI stringtypedef const wchar_t *LPCWSTR; // Pointer to const Wide stringtypedef char *LPSTR; // Pointer to ANSI stringtypedef wchar_t *LPWSTR; // Pointer to Wide string
// Handle types (all opaque pointers)typedef void *HANDLE; // Generic kernel object handletypedef HANDLE HWND; // Window handletypedef HANDLE HINSTANCE; // Module handletypedef HANDLE HDC; // Device context handletypedef HANDLE HBRUSH; // GDI brush handletypedef HANDLE HFONT; // GDI font handletypedef HANDLE HICON; // Icon handletypedef HANDLE HCURSOR; // Cursor handleThe LP Prefix
The LP prefix stands for "Long Pointer" - a relic from 16-bit Windows where there were near pointers (16-bit, within a segment) and far/long pointers (32-bit, segment:offset). On 32-bit and 64-bit Windows, all pointers are the same size, so LP is meaningless but preserved for compatibility.
LPCTSTR = LP + C + T + STR │ │ │ └── String │ │ └────── TCHAR (generic character, see below) │ └────────── Const └────────────── Long Pointer (legacy)Unicode vs ANSI: The W and A Suffixes
Most Win32 functions that take strings exist in two versions:
// ANSI version (uses char* / LPSTR)HANDLE CreateFileA(LPCSTR lpFileName, ...);
// Unicode/Wide version (uses wchar_t* / LPWSTR)HANDLE CreateFileW(LPCWSTR lpFileName, ...);
// The undecorated name is a macro:#ifdef UNICODE#define CreateFile CreateFileW#define TCHAR wchar_t#define TEXT(s) L##s#else#define CreateFile CreateFileA#define TCHAR char#define TEXT(s) s#endifModern Windows development should use the W (Unicode) versions. The A versions convert ANSI to Unicode internally and then call the W version anyway — you get extra overhead and break non-ASCII filenames for nothing.
// Recommended: use wide strings directlyCreateFileW(L"C:\\data\\file.txt", ...);
// Or use the TEXT/TCHAR macros for portability (less common today)CreateFile(TEXT("C:\\data\\file.txt"), ...);Windows uses UTF-16LE (Little Endian) for its native Unicode representation. Each wchar_t is 2 bytes. Characters outside the Basic Multilingual Plane (like emoji) use surrogate pairs (two wchar_t values). This differs from Linux which uses UTF-8 for strings and wchar_t is 4 bytes (UTF-32). The choice of UTF-16 was made in the early 1990s when Unicode was expected to fit in 16 bits.
Header Files and Linking
Win32 programming requires specific headers and libraries:
#include <windows.h> // Master header - includes most Win32 declarations// windows.h includes:// windef.h - Basic type definitions// winbase.h - Kernel32 functions (processes, files, memory)// wingdi.h - GDI drawing functions// winuser.h - User interface functions (windows, messages)// winnls.h - National language support// wincon.h - Console functions// winreg.h - Registry functions
// Additional headers for specific functionality:#include <winsock2.h> // Networking (must be before windows.h!)#include <shlobj.h> // Shell functions#include <dbghelp.h> // Debug/symbol functions#include <tlhelp32.h> // Tool Help (process/thread enumeration)Linking against Windows libraries:
// Compiler/linker commands (MSVC):cl /W4 myapp.c /link kernel32.lib user32.lib gdi32.lib
// Common import libraries:kernel32.lib - Process, thread, file, memory functionsuser32.lib - Window, message, input functionsgdi32.lib - Drawing, font, bitmap functionsadvapi32.lib - Registry, security, service functionsws2_32.lib - Winsock networking functionsshell32.lib - Shell functionsntdll.lib - Native API (undocumented)Error Handling
Win32 functions report errors through several mechanisms:
GetLastError()
Most functions that return BOOL, HANDLE, or DWORD set a per-thread error code on failure:
HANDLE hFile = CreateFile("nonexistent.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);if (hFile == INVALID_HANDLE_VALUE) { DWORD error = GetLastError(); // error = ERROR_FILE_NOT_FOUND (2)
// Get human-readable error message LPSTR message = NULL; FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, (LPSTR)&message, 0, NULL ); printf("Error %lu: %s\n", error, message); LocalFree(message);}NTSTATUS
Native API functions (Nt*/Zw*) return NTSTATUS values:
// NTSTATUS encoding:// Bits 31-30: Severity (00=Success, 01=Informational, 10=Warning, 11=Error)// Bit 29: Customer flag (1 = user-defined)// Bits 27-16: Facility code// Bits 15-0: Status code
#define STATUS_SUCCESS 0x00000000 // OK#define STATUS_ACCESS_DENIED 0xC0000022 // Error: access denied#define STATUS_OBJECT_NOT_FOUND 0xC0000034 // Error: not foundHRESULT
COM and some newer APIs use HRESULT:
// HRESULT encoding:// Bit 31: 0 = success, 1 = failure// Bits 30-16: Facility// Bits 15-0: Code
#define S_OK 0x00000000 // Success#define S_FALSE 0x00000001 // Success, but false condition#define E_FAIL 0x80004005 // Unspecified failure#define E_ACCESSDENIED 0x80070005 // Access denied
// Check with SUCCEEDED() / FAILED() macrosHRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);if (FAILED(hr)) { // Handle error}A Complete Minimal Win32 Program
Putting it all together - a minimal program that creates a window:
#include <windows.h>
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, 10, 10, TEXT("Hello, Win32!"), 13); EndPaint(hwnd, &ps); return 0; } } return DefWindowProc(hwnd, msg, wParam, lParam);}
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR cmd, int show) { WNDCLASS wc = { .lpfnWndProc = WndProc, .hInstance = hInst, .hCursor = LoadCursor(NULL, IDC_ARROW), .hbrBackground = (HBRUSH)(COLOR_WINDOW + 1), .lpszClassName = TEXT("MyClass") }; RegisterClass(&wc);
HWND hwnd = CreateWindow(TEXT("MyClass"), TEXT("My Window"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, hInst, NULL); ShowWindow(hwnd, show);
MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return (int)msg.wParam;}This covers the core Win32 patterns: registering a window class, creating a window, running a message loop, handling messages in a window procedure. We'll dig into each of these in the lessons ahead.