Pen Object (GDI)

The Pen object is a Graphics Device Interface (GDI) object used to draw lines and curves. Pens define the color, width, and style of lines drawn by various GDI functions.

Overview

A pen is a fundamental drawing primitive in GDI. It's essentially a brush that is used to outline shapes, draw straight lines, and create stroked paths. When you draw a line or the border of a shape, GDI uses the currently selected pen in the device context (DC) to perform the drawing operation.

Pen Creation

Pens can be created using the following functions:

Pens are resources that must be managed. After you are finished with a pen, you should destroy it using the DeleteObject function to free up system resources.

Pen Properties

A pen's appearance is defined by several properties:

Pen Styles

The following constants define the available pen styles:

Pen Width

For cosmetic pens created with CreatePen, the width is always 1 pixel. For pens created with ExtCreatePen, the width can be specified and applies to geometric pens.

Pen Color

The color of a pen is specified using an RGB color value (e.g., RGB(255, 0, 0) for red).

Using a Pen

To use a pen for drawing:

  1. Create the pen object using one of the creation functions.
  2. Select the pen into a device context (DC) using the SelectObject function. This returns the previously selected pen.
  3. Perform your drawing operations (e.g., LineTo, Rectangle, Polyline).
  4. When you are finished drawing, select the original pen back into the DC using SelectObject to restore the DC's state.
  5. Delete the pen object using DeleteObject.
Always remember to save and restore the previous object when using SelectObject. This is crucial for preventing resource leaks and ensuring that other parts of your application or the system can use the original objects correctly.

Example

The following C++ code snippet demonstrates how to create a blue solid pen and draw a line:


HDC hdc = GetDC(hWnd); // Get the device context
HPEN hBluePen = CreatePen(PS_SOLID, 2, RGB(0, 0, 255)); // Create a 2-pixel wide blue solid pen
HPEN hOldPen = (HPEN)SelectObject(hdc, hBluePen); // Select the new pen into the DC

// Draw a line
MoveToEx(hdc, 10, 10, NULL);
LineTo(hdc, 100, 100);

SelectObject(hdc, hOldPen); // Restore the original pen
DeleteObject(hBluePen);     // Delete the pen object
ReleaseDC(hWnd, hdc);       // Release the device context
            

See Also