Windows API Reference

Microsoft Graphics Device Interface (GDI)

CreatePen

The CreatePen function creates a logical pen that has the specified style, width, and color. A physical pen can be created by calling the ExtCreatePen function.

HPEN CreatePen(
  int fnPenStyle,
  int nWidth,
  COLORREF crColor
);

Parameters

Parameter Description
fnPenStyle The pen style. This parameter can be one of the following values:
  • PS_SOLID: A solid pen.
  • PS_DASH: A dashed pen.
  • PS_DOT: A dotted pen.
  • PS_DASHDOT: A dashed and dotted pen.
  • PS_DASHDOTDOT: A dashed, dotted, and dotted pen.
  • PS_NULL: The pen is not drawn.
  • PS_INSIDEFRAME: The pen is drawn a specified number of pixels inside the frame. This style is valid only when the pen is used to draw a frame or border around a rectangle by calling the Rectangle function.
nWidth The width of the pen, in logical units. If this parameter is zero, the pen is a single pixel wide.
crColor The color of the pen. This parameter must be a COLORREF value. To create a COLORREF value, use the RGB macro.

Return Value

If the function succeeds, the return value is an HPen handle to a new logical pen.

If the function fails, the return value is NULL.

Remarks

A logical pen is a graphical drawing tool that can be selected into a device context. Once selected, it can be used to draw lines and curves.

The width specified by nWidth is in logical units. The actual width of the pen on the display depends on the device's mapping mode and resolution.

When you no longer need the pen, call the DeleteObject function to delete it.

Example


HPEN hPen;
HDC hdc;

// Create a red, solid pen with a width of 2 logical units
hPen = CreatePen(PS_SOLID, 2, RGB(255, 0, 0));

if (hPen != NULL) {
    // Select the pen into the device context
    HPEN hOldPen = (HPEN)SelectObject(hdc, hPen);

    // Draw a line using the new pen
    MoveToEx(hdc, 10, 10, NULL);
    LineTo(hdc, 100, 100);

    // Restore the old pen
    SelectObject(hdc, hOldPen);

    // Delete the pen object
    DeleteObject(hPen);
}
            

Requirements

Header: wingdi.h

Library: gdi32.lib

DLL: gdi32.dll

See Also