Saving the DC context

The code

SaveDC.h
class CSaveDC {
    public:
       CSaveDC(CDC & dc) { sdc = &dc; saved = dc.SaveDC(); }
       CSaveDC(CDC * dc) { sdc = dc; saved = dc->SaveDC(); }
       virtual ~CSaveDC() { sdc->RestoreDC(saved); }
    protected:
       CDC * sdc;
       int saved;
};

That's all there is to it! Note that it has two constructors, one if you have a CDC * and one if you have a CDC or CDC &. All you do is declare a dummy variable. But there's an important trick, illustrated below.

void CMyView::OnPaint()
   {
    CPaintDC dc(this);
    CFont f;
    f.CreateFont(...); // parameters not shown
    { /* save context */
     CSaveDC sdc(dc);
     dc.SelectObject(&f);     dc.TextOut(...); // whatever...
    } /* save context */
   } // destructors called here..

Note that the save context you create by using the CSaveDC class must be in a scope that is smaller than the objects selected into the DC. Thus the /* save context */ block guarantees that the CSaveDC destructor is guaranteed to be called before the destructor for the font. All you have to do is declare your fonts, pens, brushes, and regions outside the /* save context */ block and you can be guaranteed that their destructors will be called in a context where they are not selected into the active DC.

Note that CSaveDCs can nest (because the ::SaveDC can nest). The nesting can be static or dynamic. For example

void CMyView::OnPaint()
   {
    CPaintDC dc(this);
    CFont f;
    f.CreateFont(12,...); // most parameters not shown
    { /* save context */
     CSaveDC sdc(dc);
     dc.SelectObject(&f);
     drawboxes(dc);
     dc.TextOut(...); // whatever...
   } // destructors called here

void CMyView::drawboxes(CDC & dc)
   {
    CPen RedPen(PS_SOLID, 0, RGB(255, 0, 0));
    CBrush GreenBrush(RGB(0, 255, 0);
    CFont f;
    f.CreateFont(6, ...); // most parameters not shown
    { /* save context */
     dc.SelectObject(&RedPen);
     dc.SelectObject(&GreenBrush);
     dc.SetBkMode(TRANSPARENT);
     dc.SetTextColor(::GetSysColor(COLOR_GRAYTEXT);
     ...
    } /* save context */
   }

Note that the save context in drawboxes contains lots of changes; these will be undone when you leave the save context, so that when drawboxes returns to OnPaint, the DC will have the correct font (12-pixel), background mode, etc.

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The difference between theory and practice is smaller in theory than in practice.”