Created: April 15, 1992
ABSTRACT
This technical note describes the MFC routines that support mapping Windows object handles to C++ objects.
The Microsoft Foundation Class (MFC) library provides a full-featured set of C++ object classes for the MicrosoftÒ WindowsÔ graphical environment. It includes classes that directly support application development for Windows as well as general-purpose classes for collections, files, persistent storage, exceptions, diagnostics, memory management, strings, and time. Each MFC technical note describes a feature of MFC using code fragments and examples.
MicrosoftÒ WindowsÔ objects are normally represented by handles. The MFCs wrap Windows object handles with C++ objects. The handle-wrapping functions of the MFC library provide a way to find the C++ object that is wrapping the Windows object with a particular handle. At times, however, a Windows object does not have a C++ wrapper object, and 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 MFC object that wraps the handle by calling the FromHandle class static function. For example, given an HWND called hWnd,
CWnd::FromHandle(hWnd)
returns a pointer to the CWnd that wraps the hWnd. If that hWnd does not have a specific wrapper object, a temporary CWnd is created to wrap the hWnd. Thus, you can get a valid C++ object from any handle.
You can associate a newly created handle wrapper object with a handle to a Windows object by calling Attach. For example:
CWnd myWnd;
myWnd.Attach(hWnd);
makes an entry in the permanent map associating myWnd and hWnd. Calling CWnd::FromHandle(hWnd) now returns a pointer to myWnd.
When myWnd is deleted, the destructor automatically destroys the hWnd by calling the Windows DestroyWindow function. If this is not desired, the hWnd must be detached from myWnd with the Detach function before the myWnd object is destroyed (normally when leaving the scope at which myWnd was defined):
myWnd.Detach();
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 handles and deleted by the DeleteTempMap function. The default OnIdle processing in CWinApp automatically calls DeleteTempMap for each class that supports temporary handle maps. Thus, you cannot assume that a pointer to a temporary object is valid past the point of exit from the function where the pointer was obtained because the temporary object is deleted during the Windows message loop idle time.