Share via


Selecting a Graphic Object into a Device Context

OverviewHow Do ITutorial

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
        pDC->MoveTo(...);
        pDC->LineTo(...);

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

Lifetime of Graphic Objects

The graphic object returned by is “temporary.” That is, it will be deleted by the 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?