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 CNewView::OnDraw(CDC* pDC)
{
   CPen penBlack;  // Construct it, then initialize
   if (penBlack.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(20, 20);
      pDC->LineTo(40, 40);

      // 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 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

See also

Graphic Objects