Skip to main content
Be Bitwise

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.

c
// Getting a DC for a window's client area
HDC 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);
Device Context State

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)

c
// Create a solid red pen, 2 pixels wide
HPEN hPen = CreatePen(PS_SOLID, 2, RGB(255, 0, 0));
HPEN hOldPen = (HPEN)SelectObject(hdc, hPen);
// Draw with the pen
MoveToEx(hdc, 10, 10, NULL);
LineTo(hdc, 200, 10); // Horizontal line
LineTo(hdc, 200, 200); // Vertical line
Rectangle(hdc, 50, 50, 150, 150); // Rectangle (pen = outline)
// Restore old pen and delete ours
SelectObject(hdc, hOldPen);
DeleteObject(hPen);
// Pen styles:
// PS_SOLID ─────────
// PS_DASH ── ── ──
// PS_DOT ··········
// PS_DASHDOT ─·─·─·─·
// PS_DASHDOTDOT ─··─··─··
// PS_NULL (invisible)

Brushes (for fills)

c
// Solid brush
HBRUSH hBrush = CreateSolidBrush(RGB(0, 128, 255));
// Hatch brush
HBRUSH hHatch = CreateHatchBrush(HS_CROSS, RGB(0, 0, 0));
// Pattern brush from bitmap
HBRUSH hPattern = CreatePatternBrush(hBitmap);
// Select and use
HBRUSH hOld = (HBRUSH)SelectObject(hdc, hBrush);
Ellipse(hdc, 10, 10, 200, 200); // Filled ellipse
SelectObject(hdc, hOld);
DeleteObject(hBrush);

Fonts

c
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 background
TextOut(hdc, 10, 10, TEXT("Hello GDI!"), 10);
// DrawText for formatted text
RECT 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

c
// Lines
MoveToEx(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 polygon
Pie(hdc, left, top, right, bottom, xStart, yStart, xEnd, yEnd);
Arc(hdc, left, top, right, bottom, xStart, yStart, xEnd, yEnd);
// Fill operations
FillRect(hdc, &rect, hBrush); // Fill rectangle
FrameRect(hdc, &rect, hBrush); // Draw rectangle border
InvertRect(hdc, &rect); // Invert colors
// Individual pixels
SetPixel(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:

c
// Copy from source DC to destination DC
BitBlt(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 scaling
StretchBlt(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.

c
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;
}
Key Concept
GDI vs Direct2D

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:

c
#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-aliasing
Pen pen(Color(255, 0, 128, 255), 2.0f);
graphics.DrawEllipse(&pen, 50, 50, 200, 150);
// Semi-transparent fill
SolidBrush brush(Color(128, 255, 0, 0)); // 50% transparent red
graphics.FillEllipse(&brush, 50, 50, 200, 150);
// Gradient brush
LinearGradientBrush 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.