This documentation is archived and is not being maintained.

Selecting a Graphic Object into a Device Context 

This topic applies to using graphic objects in a window's device context. After you create a drawing object, you must select it into the device context in place of the default object stored there:

void CMyView::OnDraw( CDC* pDC )
    CPen penBlack;  // Construct it, then initialize
    if( newPen.CreatePen( PS_SOLID, 2, RGB(0,0,0) ) )
        // Select it into the device context
        // Save the old pen at the same time
        CPen* pOldPen = pDC->SelectObject( &penBlack );

        // Draw with the pen

        // Restore the old pen to the device context
        pDC->SelectObject( pOldPen );
        // Alert the user that resources are low

The graphic object returned by SelectObject is "temporary." That is, it will be deleted by the OnIdle member function of class CWinApp 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 message loop, you will have no problem.

What do you want to know more about?