Learning Hub Search Ctrl K

MFC › 1. Getting Started

Win32 Foundations

Handles, WinMain, the window procedure and the message loop.

beginner #win32#hwnd#message-loop#wndproc#winmain#handles

Explanation

MFC is a C++ wrapper around the Win32 API, so understanding Win32 explains almost everything MFC does.

Key ideas:

  • Handles: opaque identifiers for system objects: HWND (window), HINSTANCE (module), HDC (device context), HBRUSH, HBITMAP, HMENU… You never look inside a handle; you pass it to API functions and release it when done.
  • Window class: a template registered with RegisterClass, naming the window procedure and defaults (cursor, background).
  • Window procedure (WndProc): a callback that receives every message for the window as (hWnd, msg, wParam, lParam).
  • Messages: WM_PAINT, WM_LBUTTONDOWN, WM_COMMAND, WM_DESTROY… are integers with two parameter words. Windows places them in a per-thread message queue.
  • Message loop: GetMessage pulls the next message, TranslateMessage converts key presses to WM_CHAR, DispatchMessage calls the right WndProc. GetMessage returns 0 for WM_QUIT, which ends the loop.
  • Messages you don’t handle must go to DefWindowProc.
  • Entry point: WinMain / wWinMain (GUI) instead of main.

The A/W suffix: most functions exist as ...A (ANSI) and ...W (UTF-16 Unicode) versions; windows.h maps the plain name to one of them depending on UNICODE. Always build Unicode.

Example

A complete window with no MFC (a Win32 project, Subsystem: Windows):

#include <windows.h>

LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    switch (msg) {
    case WM_PAINT: {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hWnd, &ps);                   // required in WM_PAINT
        const wchar_t text[] = L"Hello, Win32! Click me.";
        TextOutW(hdc, 20, 20, text, lstrlenW(text));
        EndPaint(hWnd, &ps);
        return 0;
    }
    case WM_LBUTTONDOWN:
        MessageBoxW(hWnd, L"You clicked the window.", L"Win32", MB_OK);
        return 0;
    case WM_DESTROY:
        PostQuitMessage(0);                                // puts WM_QUIT in the queue
        return 0;
    }
    return DefWindowProcW(hWnd, msg, wParam, lParam);      // default handling for everything else
}

int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE, PWSTR, int nCmdShow) {
    WNDCLASSW wc = {};
    wc.lpfnWndProc   = WndProc;
    wc.hInstance     = hInst;
    wc.lpszClassName = L"DemoWindow";
    wc.hCursor       = LoadCursor(nullptr, IDC_ARROW);
    wc.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_WINDOW + 1);
    RegisterClassW(&wc);

    HWND hWnd = CreateWindowExW(0, wc.lpszClassName, L"Win32 Demo", WS_OVERLAPPEDWINDOW,
                                CW_USEDEFAULT, CW_USEDEFAULT, 480, 320,
                                nullptr, nullptr, hInst, nullptr);
    if (!hWnd) return 1;
    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    MSG msg;
    while (GetMessage(&msg, nullptr, 0, 0) > 0) {          // 0 = WM_QUIT, -1 = error
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return static_cast<int>(msg.wParam);
}

Common pitfalls

  • Forgetting DefWindowProc leaves the window unable to move, resize or close.
  • while (GetMessage(...)) treats the error return -1 as true and spins forever; test > 0.
  • Doing long work inside a WndProc freezes the UI because the message loop can’t run. Use a worker thread (see Threads and Timers).
  • GDI leaks: every CreatePen/CreateFont/CreateCompatibleDC needs the matching Delete...; the system has a limit (about 10,000 handles per process).
  • BeginPaint only in WM_PAINT; elsewhere use GetDC/ReleaseDC.
  • Mixing ANSI and Unicode strings gives garbage or compile errors: use TCHAR, _T("") or explicit W calls consistently.

MFC equivalent

MFC hides all of this: CWinApp::InitInstance replaces wWinMain, CWnd wraps an HWND, and a message map replaces the switch in WndProc. CWinApp::Run is the message loop. See Hello MFC.

Exercises

1. Why must WndProc call PostQuitMessage in response to WM_DESTROY?

Destroying the window doesn’t end the thread’s message loop. PostQuitMessage posts WM_QUIT, which makes GetMessage return 0 so the loop exits and the program ends.