Creating, Selecting, and Deleting Drawing Tools

GDI lets you use a variety of drawing tools to draw within a window. It provides pens to draw lines, brushes to fill interiors, and fonts to write text. To create these tools, use functions such as CreatePen and CreateSolidBrush. Then select them into the display context by using the SelectObject function. When you are done using a drawing tool, you can delete it by using the DeleteObject function.

Use the CreatePen function to create a pen for drawing lines and borders. The function returns a handle to a pen that has the specified style, width, and color. (Be sure to check the return value of CreatePen to ensure that it is a valid handle.)

The following example creates a dashed, black pen, one pixel wide:

HPEN hDashPen;

.

.

.

hDashPen = CreatePen(PS_DASH, 1, RGB(0, 0, 0));

if (hDashPen) /* make sure handle is valid */

.

.

.

The RGB macro creates a 32-bit value representing a red, green, and blue color value. The three arguments specify the intensity of the colors red, green, and blue, respectively. In this example, all colors have zero intensity, so the specified color is black.

You can create solid brushes for drawing and filling by using the CreateSolidBrush function. This function returns a handle to a brush that contains the specified solid color. (Be sure to check the return value of CreateSolidBrush to ensure that it is a valid handle.)

The following example shows how to create a red brush:

HBRUSH hRedBrush

.

.

.

hRedBrush = CreateSolidBrush(RGB(255, 0, 0));

if (hRedBrush) /* make sure handle is valid */

.

.

.

Once you have created a drawing tool, you can select it into a display context by using the SelectObject function. The following example selects the red brush for drawing:

HBRUSH hOldBrush;

.

.

.

hOldBrush = SelectObject(hDC, hRedBrush);

In this example, SelectObject returns a handle to the previous brush. In general, you should save the handle of the previous drawing tool so that you can restore it later.

You do not have to create or select a drawing tool before using a display context. Windows provides default drawing tools with each display context; for example, a black pen, a white brush, and the system font.

You can delete drawing objects you no longer need by using the DeleteObject function. The following example deletes the brush identified by the handle hRedBrush:

DeleteObject(hRedBrush);

You must not delete a selected drawing tool. You should use the SelectObject function to restore a previous drawing tool and remove the tool to be deleted from the selection, as shown in the following example:

SelectObject(hDC, hOldBrush);

DeleteObject(hRedBrush);

Although you can select fonts for writing text, working with fonts is a fairly involved process and is not described in this chapter. For a full discussion of how to select fonts, see Chapter 27.