3.2 Creating, Selecting, and Deleting Drawing Tools

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

Use the CreatePen function to create a pen for drawing lines and borders. This function returns a handle of a pen that has the specified style, width, and color. (Always 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 != NULL)   /* makes sure handle is valid    */
    .
    .
    .

The RGB macro creates a 32-bit color value representing a mix of red, green, and blue intensities. 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 of a brush that contains the specified solid color. (Always check the return value of CreateSolidBrush to ensure that it is a valid handle.)

The following example creates a red brush:

HBRUSH hRedBrush
    .
    .
    .

hRedBrush = CreateSolidBrush(RGB(255, 0, 0));
if (hRedBrush != NULL)    /* makes sure handle is valid */
    .
    .
    .

Once you have created a drawing tool, you can select it into a device 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 device context. Windows provides default drawing tools with each device 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. Instead, use the SelectObject function to restore a previous drawing tool and remove the tool to be deleted from the selection, as in the following example:

SelectObject(hDC, hOldBrush);
DeleteObject(hRedBrush);

Although you can create and select fonts for writing text, working with fonts is a fairly complex process and is not described in this chapter. For more information about creating and selecting fonts, see Chapter 18, “Fonts.”