5.1. CDC

Microsoft Visual C++/Microsoft Foundation Classes


5.1. CDC

5.1.1. How do I create a CDC from a HDC?

Sometimes the Windows API will just give you a handle to a DC and you might want to create a CDC from that. One example is owner-drawn lists, combos, and buttons. You will receive a draw item message with a hDC. Here's some code to turn that hdc into the more familiar CDC.

You can use this technique for any of the other MFC class/ Windows handle pairs too.

void MyODList::DrawItem(LPDRAWITEMSTRUCT lpDrawItem)
{
    CDC myDC;
    myDC.Attach(lpDrawItem->hDC);
    //Do more stuff here
    //If you don't detach, it will get deleted and windows will
    //not be happy if you delete it's dc..
    myDC.Detach();
}

Another approach is to call the CDC FromHandle method:

CDC* pDC = CDC:FromHandle(lpDrawItem->hDC);

It's not clear which is 'better', FromHandle() is less error prone because you do not have to remember to 'detach'.

[email protected] (Jim McCabe) 6/5/95