Skip to content

Basic Window

The smallest complete Win32 window program: register a class, create a window, run the message loop.

Published Jun 30, 1999

Every Win32 GUI starts with these four moves: fill in a WNDCLASS, RegisterClass it, CreateWindow an instance, and pump messages until WM_QUIT. This is that skeleton in its entirety, with a WndProc that quits on WM_CLOSE and pops a message box on any keypress so you can confirm the loop is alive. Use it as the blank page whenever you are starting from raw Win32 instead of a dialog template.

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <Windows.H>

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

LRESULT CALLBACK WndProc (HWND hWindowHandle, UINT iWindowMessage, WPARAM wParam, LPARAM lParam);

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	WNDCLASS MyWndClass;
	MyWndClass.hCursor       = LoadCursor(NULL, IDC_ARROW);
	MyWndClass.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
	MyWndClass.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
	MyWndClass.hInstance     = hInstance;
	MyWndClass.lpfnWndProc   = WndProc;
	MyWndClass.lpszClassName = "BasicWindowClass";
	MyWndClass.lpszMenuName  = NULL;
	MyWndClass.cbClsExtra    = NULL;
	MyWndClass.cbWndExtra    = NULL;
	MyWndClass.style         = NULL;

	if(!RegisterClass(&MyWndClass))
		return -1;

	HWND hWindowHandle;
	hWindowHandle = CreateWindow("BasicWindowClass", "MyTitle", WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);


	MSG kWindowMessage;
	while (GetMessage(&kWindowMessage, hWindowHandle, 0,0))
	{
		TranslateMessage(&kWindowMessage);
		DispatchMessage(&kWindowMessage);
	}
	return 0;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

LRESULT CALLBACK WndProc(HWND hWindowHandle, UINT iWindowMessage, WPARAM wParam, LPARAM lParam)
{
	switch (iWindowMessage)
	{
	case WM_CLOSE:
		PostQuitMessage(0);
		break;
	case WM_KEYDOWN:
		MessageBox(hWindowHandle, "You pressed a key.", "Title", 0);
		break;
	default:
		return DefWindowProc (hWindowHandle, iWindowMessage, wParam, lParam);
	}
	return 0;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
An unhandled error has occurred. Reload 🗙