Attaching and Detaching Objects

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.

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.

“There's no test like production” - Anon