Library tutorials & articles

Attaching and Detaching Objects

Attaching handles

There is a corresponding operation to Detach, which is Attach. The Attach operation takes a HANDLE argument of the appropriate type and attaches that handle to an existing MFC object. The MFC object must not already have a handle attached.

Thus, if I buy a third-party DLL that tells me that one of its functions returns an HFONT, or an HWND, or an HPEN, or any other handle, I can attach that object to a corresponding already-existing MFC object by using Attach. Consider that I've got a DLL which has an operation getCoolPen for the operations it wants to do. It returns an HPEN, which I can store. But it may be convenient for me to store that as an MFC object. One way to do this is to declare, for example in a CView-derived class, a member variable (probably a protected member variable), 

CPen myCoolPen;

I can then do something like

void CMyView::OnInitialUpdate()
     {
      // ...
       myCoolPen.Attach(getCoolPen());
      // ...
     }

Note that this requires that you understand the implications of the getCoolPen call. If the DLL writer has properly documented the product, it will state explicitly if you must delete the HPEN when you are done with it, or must not delete the HPEN because it is shared. Often such useful information is only determinable by reading the sides of airborne porcine creatures. But let's assume that we actually know what should be done. 

In the case where you must delete the HPEN when you are no longer interested in it, you don't need to do anything special. When the view is destroyed, the destructors for all its members are called, which means the CPen destructor is called, deleting the underlying HPEN.

In the case where you must not delete the HPEN because it is shared, you must add to the destructor for your CView-derived class a line like the one shown below:

CMyView::~CMyView()
   {
    // ...
    myCoolPen.Detach();
    // ...
   }

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

We'd love to hear what you think! Submit ideas or give us feedback