Windows GDI & Drawing
Windows API - GUI & System Programming · Windows Programming track
10 min read
In this module
Drawing on the Screen with GDI
The Graphics Device Interface (GDI) is Windows' original drawing API, dating back to the mid-80s when "graphics card" meant a 16-colour EGA. New code reaches for Direct2D, DirectWrite, or some GPU-backed framework these days. Even so, GDI is still everywhere underneath: open any WM_PAINT handler in the Windows codebase and somewhere down the call stack you'll find a HDC and a SelectObject. If you want to understand how pixels actually arrive on a Windows screen, GDI is where the conversation starts.
Device Contexts
A Device Context (DC) is the canvas. It's also a state machine: a HDC remembers your current pen, brush, font, text colour, background mode, and coordinate transform. You don't pass those parameters to every call; you select them into the DC once and they stick until you change them again.
// Getting a DC for a window's client areaHDC hdc = GetDC(hwnd);// ... draw ...ReleaseDC(hwnd, hdc); // Must release when done
// In WM_PAINT handler (preferred)PAINTSTRUCT ps;HDC hdc = BeginPaint(hwnd, &ps);// Drawing is clipped to ps.rcPaint (invalid region)// ... draw ...EndPaint(hwnd, &ps); // Validates the region
// Memory DC for off-screen drawing (double buffering)HDC hdcMem = CreateCompatibleDC(hdc);HBITMAP hBitmap = CreateCompatibleBitmap(hdc, width, height);HBITMAP hOld = (HBITMAP)SelectObject(hdcMem, hBitmap);// Draw to hdcMem (off-screen)...// Then copy to screen:BitBlt(hdc, 0, 0, width, height, hdcMem, 0, 0, SRCCOPY);SelectObject(hdcMem, hOld);DeleteObject(hBitmap);DeleteDC(hdcMem);A DC maintains drawing state including: the selected pen (for lines and outlines), brush (for fills), font (for text), text colour, background colour and mode, clipping region, and coordinate transformation. When you select a new object into a DC with SelectObject(), the old object is returned and must be restored before the DC is released. Failing to restore objects causes GDI resource leaks.
Pens, Brushes, and Fonts
Pens (for lines and outlines)
// Create a solid red pen, 2 pixels wideHPEN hPen = CreatePen(PS_SOLID, 2, RGB(255, 0, 0));HPEN hOldPen = (HPEN)SelectObject(hdc, hPen);
// Draw with the penMoveToEx(hdc, 10, 10, NULL);LineTo(hdc, 200, 10); // Horizontal lineLineTo(hdc, 200, 200); // Vertical lineRectangle(hdc, 50, 50, 150, 150); // Rectangle (pen = outline)
// Restore old pen and delete oursSelectObject(hdc, hOldPen);DeleteObject(hPen);
// Pen styles:// PS_SOLID ─────────// PS_DASH ── ── ──// PS_DOT ··········// PS_DASHDOT ─·─·─·─·// PS_DASHDOTDOT ─··─··─··// PS_NULL (invisible)Brushes (for fills)
// Solid brushHBRUSH hBrush = CreateSolidBrush(RGB(0, 128, 255));
// Hatch brushHBRUSH hHatch = CreateHatchBrush(HS_CROSS, RGB(0, 0, 0));
// Pattern brush from bitmapHBRUSH hPattern = CreatePatternBrush(hBitmap);
// Select and useHBRUSH hOld = (HBRUSH)SelectObject(hdc, hBrush);Ellipse(hdc, 10, 10, 200, 200); // Filled ellipseSelectObject(hdc, hOld);DeleteObject(hBrush);Fonts
HFONT hFont = CreateFont( 24, // Height (negative = character height) 0, // Width (0 = default aspect ratio) 0, // Escapement angle (tenths of degree) 0, // Orientation angle FW_BOLD, // Weight (FW_NORMAL, FW_BOLD) FALSE, // Italic FALSE, // Underline FALSE, // Strikeout DEFAULT_CHARSET, // Character set OUT_DEFAULT_PRECIS, // Output precision CLIP_DEFAULT_PRECIS,// Clipping precision CLEARTYPE_QUALITY, // Quality DEFAULT_PITCH | FF_SWISS, // Pitch and family TEXT("Segoe UI") // Font face name);
HFONT hOldFont = (HFONT)SelectObject(hdc, hFont);SetTextColor(hdc, RGB(0, 0, 0));SetBkMode(hdc, TRANSPARENT); // Don't fill text backgroundTextOut(hdc, 10, 10, TEXT("Hello GDI!"), 10);
// DrawText for formatted textRECT rc = { 10, 50, 300, 200 };DrawText(hdc, TEXT("This is a paragraph of text that will word-wrap within the rectangle."), -1, &rc, DT_WORDBREAK | DT_LEFT);
SelectObject(hdc, hOldFont);DeleteObject(hFont);Drawing Primitives
// LinesMoveToEx(hdc, x1, y1, NULL);LineTo(hdc, x2, y2);Polyline(hdc, points, numPoints); // Connected line segments
// Shapes (filled with current brush, outlined with current pen)Rectangle(hdc, left, top, right, bottom);Ellipse(hdc, left, top, right, bottom);RoundRect(hdc, left, top, right, bottom, widthEllipse, heightEllipse);Polygon(hdc, points, numPoints); // Filled polygonPie(hdc, left, top, right, bottom, xStart, yStart, xEnd, yEnd);Arc(hdc, left, top, right, bottom, xStart, yStart, xEnd, yEnd);
// Fill operationsFillRect(hdc, &rect, hBrush); // Fill rectangleFrameRect(hdc, &rect, hBrush); // Draw rectangle borderInvertRect(hdc, &rect); // Invert colors
// Individual pixelsSetPixel(hdc, x, y, RGB(255, 0, 0));COLORREF color = GetPixel(hdc, x, y);BitBlt and Raster Operations
BitBlt — short for Bit Block Transfer, pronounced "bit-blit" by anyone who's worked with it long enough — copies rectangular blocks of pixels from one DC to another:
// Copy from source DC to destination DCBitBlt(hdcDest, // Destination DC xDest, yDest, // Destination position width, height, // Size hdcSrc, // Source DC xSrc, ySrc, // Source position SRCCOPY); // Raster operation
// Common raster operations:// SRCCOPY - Direct copy (most common)// SRCPAINT - Source OR destination// SRCAND - Source AND destination// SRCINVERT - Source XOR destination// NOTSRCCOPY - Inverted source copy// BLACKNESS - Fill with black// WHITENESS - Fill with white
// StretchBlt for scalingStretchBlt(hdcDest, xDest, yDest, destWidth, destHeight, hdcSrc, xSrc, ySrc, srcWidth, srcHeight, SRCCOPY);Double Buffering
Drawing straight to the screen flickers, because the user gets to watch each step of your render. The fix is double buffering: do all the drawing on an off-screen bitmap, then BitBlt the finished frame across in one call.
case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &ps);
// Create off-screen buffer RECT rc; GetClientRect(hwnd, &rc); HDC hdcMem = CreateCompatibleDC(hdc); HBITMAP hBmp = CreateCompatibleBitmap(hdc, rc.right, rc.bottom); HBITMAP hOldBmp = (HBITMAP)SelectObject(hdcMem, hBmp);
// Draw everything to the buffer (no flicker) FillRect(hdcMem, &rc, (HBRUSH)(COLOR_WINDOW + 1)); // ... all drawing operations on hdcMem ... Ellipse(hdcMem, 50, 50, 200, 200); TextOut(hdcMem, 10, 10, TEXT("Smooth!"), 7);
// Copy buffer to screen in one operation BitBlt(hdc, 0, 0, rc.right, rc.bottom, hdcMem, 0, 0, SRCCOPY);
// Cleanup SelectObject(hdcMem, hOldBmp); DeleteObject(hBmp); DeleteDC(hdcMem);
EndPaint(hwnd, &ps); return 0;}GDI is software-rendered and runs on the CPU. It is simple but slow for complex graphics. Direct2D (introduced in Windows 7) is hardware-accelerated using the GPU, providing much better performance for 2D graphics. Direct2D supports anti-aliasing, alpha blending, geometry operations, and effects that GDI cannot efficiently perform. Modern applications should use Direct2D or a framework that uses it internally.
GDI+ for Modern Drawing
GDI+ is what Microsoft shipped in Windows XP when developers got tired of jagged lines. It adds anti-aliasing, alpha blending, gradient fills, and path-based drawing on top of the GDI substrate:
#include <gdiplus.h>using namespace Gdiplus;
// Initialise GDI+ (once, at application startup)GdiplusStartupInput gdiplusStartupInput;ULONG_PTR gdiplusToken;GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
// In WM_PAINT:Graphics graphics(hdc);graphics.SetSmoothingMode(SmoothingModeAntiAlias);
// Draw with anti-aliasingPen pen(Color(255, 0, 128, 255), 2.0f);graphics.DrawEllipse(&pen, 50, 50, 200, 150);
// Semi-transparent fillSolidBrush brush(Color(128, 255, 0, 0)); // 50% transparent redgraphics.FillEllipse(&brush, 50, 50, 200, 150);
// Gradient brushLinearGradientBrush gradBrush( Point(0, 0), Point(200, 200), Color(255, 0, 0), Color(0, 0, 255));graphics.FillRectangle(&gradBrush, 10, 10, 200, 200);
// Cleanup (at application exit)GdiplusShutdown(gdiplusToken);GDI sticks around because Windows itself still uses it. The window manager, the system menus, the scroll bars, plenty of legacy controls — all GDI under the hood. There's also a security angle. The kernel-mode chunk of GDI lives in win32k.sys, and over the years it has produced an embarrassment of local privilege-escalation bugs. Anyone hunting Windows kernel exploits has spent time staring at GDI internals.