Selecting a Graphic Object into a Device Context
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

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?

© 2016 Microsoft