Library tutorials & articles

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.

Comments

  1. 13 Sep 2006 at 07:43

    Sorry posted in wrong thread

  2. 13 Sep 2006 at 06:14
    Hi

    i am new to VC++, while creating a model dialog from a cwnd class i am getting a Assertion error.
    can any one tell me where i did wrong.

    class CAuthen:: public CWnd
    {
      ............
    ..
    public:
     
    CAuthenDlg auth_dlg;
    ..

    public :

     void checkAuthentication();
     

    };

    void CAuthen :: checkAuthentication()
    {
    ..
    ..
    ..

       if(  auth_dlg.DoModal() == IDOK)
        {
           ...
           // some operation goes here
        }
    ..
    ..
    }



































  3. 01 Jan 1999 at 00:00

    This thread is for discussions of Attaching and Detaching Objects.

Leave a comment

Sign in or Join us (it's free).

Joseph M. Newcomer

Want to stay in touch with what's going on? Follow us on twitter!