Microsoft Foundation Classes                           Microsoft Corporation
Technical Notes            

#3 : Handle Maps

This note describes the MFC routines for supporting mapping Windows object
handles to C++ objects.

=============================================================================

The Problem
===========

Windows objects are normally represented by HANDLEs.  The Foundation 
classes wrap Windows object handles with C++ objects.  The handle wrapping
functions of the Foundation class library provide a way to find the C++
object that is wrapping the Windows object with a particular handle.  There
are times when a Windows object does not have a C++ wrapper object, however,
and at these times a temporary object is created to act as the C++ wrapper.


The Windows objects that use handle maps are:

    HWND
    HDC
    HMENU
    HPEN
    HBRUSH
    HFONT
    HBITMAP
    HPALETTE
    HRGN

Given a handle to any of these objects, you can find the Foundation object
that wraps the handle by calling the class static function FromHandle.  For
example, given an HWND called hWnd

    CWnd::FromHandle(hWnd)

will return a pointer to the CWnd that wraps the hWnd.  If that hWnd
does not have a specific wrapper object, then a temporary CWnd is
created to wrap the hWnd.  This makes it possible to get a valid C++
object from any handle.

=============================================================================
Attaching Handles to Foundation Objects
=======================================

Given a newly created handle wrapper object and a handle to a Windows object,
you can associate the two by calling Attach.  For example:

    CWnd myWnd;
    myWnd.Attach(hWnd);

This makes an entry in the permanent map associating myWnd and hWnd.
Calling CWnd::FromHandle(hWnd) will now return a pointer to myWnd.

Extending this example, when myWnd is deleted the destructor will
automatically destroy the hWnd, by calling the *Windows*
DestroyWindow function.  If this is not desired, the hWnd must be
detached from myWnd before the myWnd object is destroyed (normally
when leaving the scope at which myWnd was defined.  The Detach
function does this.

    myWnd.Detach();



=============================================================================
More About Temporary Objects
============================

Temporary objects are created whenever FromHandle is given a handle
that does not already have a wrapper object.  These temporary objects
are detached from their handle and deleted by the DeleteTempMap
functions.  The default OnIdle processing in CWinApp automatically
calls DeleteTempMap for each class that supports temporary handle
maps.  This means that you cannot assume a pointer to a temporary
object will be valid past the point of exit from the function where
the pointer was obtained, as the temporary object will be deleted during
the Windows message loop idle time.
