Selecting a Drawing Object into a Device Context

The previous section described how to create Microsoft Foundation graphic objects. However, before you can use these objects to draw, you must select them into a device context. By selecting a graphic object into a device context, you are modifying the drawing environment for the device context. This is the standard programming model for traditional Windows programming as well as for the Microsoft Foundation classes.

The Microsoft Foundation device context classes (CPaintDC, CClientDC, and CWindowDC) provide the SelectObject member function. You supply a pointer to a graphic object and SelectObject selects the object into the device context, returning a pointer to the previous graphic object for the device context.

For instance, if you call SelectObject with a CPen pointer, SelectObject will return a CPen pointer for the old device context pen. You can later select the old pen back into the device context to restore the original drawing state. Likewise, SelectObject will return a CFont pointer when you select a new CFont, and a CBrush pointer when you select a new CBrush.

The following example shows how to create a CPen object, select it into the device context, do some drawing, and then restore the original pen; all in the context of responding to a WM_PAINT message.

void CMyWnd::OnPaint()

{

CPaintDC myDC( this );

// create the pen

CPen newPen( PS_SOLID, 2, RGB( 0, 0, 255 ) );

// select it into the device context

// save old pen at the same time

CPen* pOldPen = myDC.SelectObject( &newPen );

// draw some lines with the pen

myDC.MoveTo(...);

myDC.LineTo(...);

myDC.LineTo(...);

myDC.LineTo(...);

// now restore old pen

myDC.SelectObject( pOldPen );

}

Note:

The graphic object returned by SelectObject is a “temporary” object. That is, it will be deleted by CWinApp::OnIdle the next time the program gets idle time. As long as you use the object returned by SelectObject in a single function without returning control to the main event loop, you will have no problem. But if you try to use the object later, after you have exited the function and the program has executed its event loop again, you risk having the object deleted by the idle time handler. See “Tracking the Mouse in a Window” on page 353 for an example of how to avoid problems when using a temporary graphic object.