Search code examples
winapimfcgdi

Does CClientDC guarantee restoring the DC back to its previous state?


I am using a CClientDC object, which serves as a wrapper for functions GetDC and ReleaseDC:

  • Function GetDC is called from inside the CClientDC constructor
  • Function ReleaseDC is called from inside the CClientDC destructor

In between, I manipulate the DC (changing pens, brushes, etc).

But I'm pretty sure that the CClientDC object does not restore the DC back to its previous state.

This means I have to make sure of it myself. Is that correct?

Thank you.


Solution

  • Open wingdi.cpp from the MFC source code and look for the implementation of CClientDC:

    CClientDC::~CClientDC()
    {
        ASSERT(m_hDC != NULL);
        ::ReleaseDC(m_hWnd, Detach());
    }
    

    You see that it only calls ReleaseDC, which does not restore the DC to its previous state. There is no way for CClientDC to know which GDI objects you changed.

    If you want to save and restore the DC's state, there are special methods for this: CDC::SaveDC and CDC::RestoreDC. These are not called automatically from CDC or CClientDC—you need manually call them yourself.

    Or, you can save and restore each individual GDI object that you modify. When you call SelectObject, the original object is returned. You save this, and restore it as you deselect the object you were using.