Summary
While this essay has concentrated primarily on the CFont object, the
techniques here apply to all MFC classes that are wrappers for Windows objects.
CGDIObject, the superclass of CPen, CBrush, CFont, CRgn, CPalette,
and others is where Attach, Detach, and FromHandle are
implemented. Subclasses such as CPen override FromHandle to take
an HPEN and return a CPen *, but in fact they simply call the superclass
to do all the work and provide the type casting necessary to make things work
right in a C++ environment. In addition, the CWnd class has Attach,
Detach, and FromHandle. The CWnd class has one other operation,
FromHandlePermanent, which I may someday write about, but not right now.
All of these operations are designed to allow you to move freely between the
Windows object domain, where objects are represented by instances of HANDLEs,
and the MFC object domain, where objects are represented by class instances of
C++ classes. It can help you a lot to understand the relationship between these
two representations, and how to use them in a safe and non-leaking fashion.