MSDN Community

Your resource for Microsoft Development

Windows Graphics Device Interface (GDI)

The Graphics Device Interface (GDI) is a core component of the Windows operating system that provides applications with a consistent and efficient way to interact with graphical output devices, such as displays and printers. GDI abstracts the complexities of different hardware capabilities, allowing developers to draw lines, curves, text, images, and other graphical elements without needing to know the specifics of the target device.

Key Concept: GDI operates on a device context (DC), which is a structure that holds information about the drawing attributes and the target device. All drawing operations are performed within a device context.

Core Components and Concepts

Key GDI Functions and Usage

Developers interact with GDI through a set of Win32 API functions. Here are some fundamental examples:

Getting a Device Context:

Before drawing, you need to obtain a handle to a device context. For a window, this is often done using GetDC.

HDC hdc = GetDC(hWnd);
// ... drawing operations ...
ReleaseDC(hWnd, hdc);

Drawing a Line:

Using a pen to draw a line requires selecting the pen into the DC and then calling LineTo.

HPEN hOldPen = (HPEN)SelectObject(hdc, hPen); // Select your pen
MoveToEx(hdc, x1, y1, NULL); // Move to the start point
LineTo(hdc, x2, y2);       // Draw the line
SelectObject(hdc, hOldPen); // Restore the old pen

Drawing Text:

Drawing text involves selecting a font and using TextOut.

HFONT hOldFont = (HFONT)SelectObject(hdc, hFont); // Select your font
TextOut(hdc, x, y, lpszString, nCount);           // Draw the string
SelectObject(hdc, hOldFont);                      // Restore the old font

Filling a Rectangle:

Filling a rectangle with a brush.

HBRUSH hOldBrush = (HBRUSH)SelectObject(hdc, hBrush); // Select your brush
Rectangle(hdc, left, top, right, bottom);        // Draw and fill the rectangle
SelectObject(hdc, hOldBrush);                     // Restore the old brush

Evolution and Modern Alternatives

While GDI has been a cornerstone of Windows graphics for decades, it has evolved. Newer technologies like GDI+ (introduced with Windows XP) and DirectX offer more advanced features, better performance, and richer graphical capabilities, especially for complex 2D and 3D graphics, animations, and rich media. However, GDI remains relevant for many standard Windows UI elements and simpler drawing tasks due to its ubiquity and efficiency for basic graphics.

Further Resources