Windows Graphics Device Interface (GDI)

The Windows Graphics Device Interface (GDI) is a core component of the Microsoft Windows operating system responsible for presenting graphical objects to displays, printers, and other output devices. GDI provides a device-independent way for applications to draw lines, curves, text, and graphical primitives.

This documentation covers the GDI API, its functions, structures, and concepts for developing graphical applications on Windows.

Key Concepts

Core GDI Functions

Here are some of the fundamental GDI functions you will frequently use:

Function Name Description
CreatePen Creates a new pen that can be selected into a device context.
CreateSolidBrush Creates a solid brush with the specified color.
SelectObject Selects a graphical object into a device context.
MoveToEx Updates the current position of the device context.
LineTo Draws a line from the current position to the specified point.
Rectangle Draws a rectangle.
TextOut Writes a string of characters at the specified location.
GetDC Retrieves a handle to a device context for a client area of a specified window.
ReleaseDC Releases a device context, freeing the memory associated with it.

Structures

GDI uses various structures to define graphical properties and coordinates:

Example: Drawing a Rectangle

Here's a simple C++ example demonstrating how to draw a rectangle using GDI:


#include <windows.h>

void DrawMyRectangle(HDC hdc)
{
    // Create a blue pen
    HPEN hPen = CreatePen(PS_SOLID, 2, RGB(0, 0, 255));
    // Create a light gray brush
    HBRUSH hBrush = (HBRUSH)GetStockObject(LTGRAY_BRUSH);

    // Select the pen and brush into the device context
    HPEN hOldPen = (HPEN)SelectObject(hdc, hPen);
    HBRUSH hOldBrush = (HBRUSH)SelectObject(hdc, hBrush);

    // Define the rectangle's coordinates
    RECT rect = { 50, 50, 200, 150 }; // { left, top, right, bottom }

    // Draw the rectangle
    Rectangle(hdc, rect.left, rect.top, rect.right, rect.bottom);

    // Restore the original pen and brush
    SelectObject(hdc, hOldPen);
    SelectObject(hdc, hOldBrush);

    // Clean up the created pen and brush
    DeleteObject(hPen);
    DeleteObject(hBrush);
}
            

Further Reading

Last Updated: October 26, 2023