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();
// ...
}