Using Stock Pens

When you call LineTo, PolyLine, or Arc, Windows uses the ”pen“ currently selected in the device context to draw the line. The pen determines the line's color, its width, and its style, which can be solid, dotted, or dashed. The pen in the default device context is called BLACK_PEN. This pen draws a solid black line with a width of one pixel regardless of the mapping mode. BLACK_PEN is one of three ”stock pens“ that Windows provides. The other two are WHITE_PEN and NULL_PEN. NULL_PEN is a pen that doesn't draw. You can also create your own customized pens.

In your Windows programs, you refer to pens with a handle. WINDOWS.H includes a type definition named HPEN, a handle to a pen. You can define a variable (for instance, hPen) using this type definition:

HPEN hPen ;

You obtain the handle to one of the stock pens by a call to GetStockObject. For instance, suppose you want to use the stock pen called WHITE_PEN. You get the pen handle like this:

hPen = GetStockObject (WHITE_PEN) ;

Now you must make that pen the currently selected pen in the device context, which requires a call to SelectObject:

SelectObject (hdc, hPen) ;

After this call, the lines you draw using LineTo, PolyLine, or Arc will use WHITE_PEN until you select another pen into the device context or release the device context.

Rather than explicitly defining an hPen variable, you can instead combine the GetStockObject and SelectObject calls in one statement:

SelectObject (hdc, GetStockObject (WHITE_PEN)) ;

If you then want to return to using BLACK_PEN, you can get the handle to that stock object and select it into the device context in one statement:

SelectObject (hdc, GetStockObject (BLACK_PEN)) ;

SelectObject returns the handle to the pen that had been previously selected into the device context. If you start off with a fresh device context and call:

hPen = SelectObject (hdc, GetStockObject (WHITE_PEN)) ;

then the current pen in the device context will be WHITE_PEN, and the variable hPen will be the handle to BLACK_PEN. You can then select BLACK_PEN into the device context by calling:

SelectObject (hdc, hPen) ;