Windows API Fundamentals

Introduction

The Windows API (WinAPI) provides a comprehensive set of functions and data structures that enable developers to interact directly with the Windows operating system. This guide covers the fundamental concepts you need to build robust native Windows applications.

Core Concepts

  • Handles: Opaque references to system resources such as windows, files, and devices.
  • Message Loop: The heart of a GUI application, processing messages from the system.
  • Modules: DLLs and EXEs that expose exported functions.
  • Unicode vs ANSI: Prefer the Unicode (W) API versions for modern applications.

Sample Code – Creating a Simple Window

#include <windows.h>

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    switch (msg) {
        case WM_DESTROY:
            PostQuitMessage(0);
            return 0;
        default:
            return DefWindowProc(hwnd, msg, wParam, lParam);
    }
}

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmd, int nShow) {
    const wchar_t CLASS_NAME[] = L"SampleWindowClass";

    WNDCLASS wc = {0};
    wc.lpfnWndProc   = WndProc;
    wc.hInstance     = hInst;
    wc.lpszClassName = CLASS_NAME;

    RegisterClass(&wc);

    HWND hwnd = CreateWindowEx(
        0,
        CLASS_NAME,
        L"Hello, Windows API!",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 500, 400,
        NULL, NULL, hInst, NULL
    );

    if (hwnd == NULL) return 0;

    ShowWindow(hwnd, nShow);
    UpdateWindow(hwnd);

    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return (int)msg.wParam;
}

This minimal example registers a window class, creates a window, and runs a basic message loop.

Additional Resources