Article ID: 85518 - Last Review: November 21, 2006 - Revision: 3.1 INFO: Correct Use of the SetFont() Function in MFCThis article was previously published under Q85518 On This PageSUMMARY
The SetFont() member function of the CWnd class changes the font in a
specified control. For this function to work correctly in a Windows-
based application, you must ensure that the CFont object specified in
the SetFont() call is not destroyed until after the specified control
has been destroyed.
MORE INFORMATION
The SetFont() accepts a CFont object as a parameter; the control uses
the specified font to display its text. The SetFont() function is
implemented to send a WM_SETFONT message to the control with the font
handle that corresponds to the CFont object. An application can delete the font specified in a WM_SETFONT message only under certain circumstances; these same restrictions apply to the CFont object specified in a SetFont() call. Specifically, do not destroy the specified CFont object until after the CWnd control has been destroyed. Windows does not copy the font specified in a SetFont() call. If the font is destroyed before the control is destroyed, unpredictable results can occur. For example, when an application uses SetFont() to change the font a dialog box uses, the application should not destroy the CFont object until after it has destroyed the dialog box. Make the CFont object a member variable of the derived dialog box class instead of making the font a local variable in one of the functions in the class. This is the best method to ensure that the CFont object exists for the lifetime of the dialog box. When the application destroys the dialog box, the dialog box class destructor automatically calls the CFont destructor to delete the font handle. The best time to specify the font for any controls in the dialog box is in the OnInitDialog() member function. The code below demonstrates deriving a dialog box class from CModalDialog and using the SetFont() member function: Sample CodeAPPLIES TO
| Article Translations
|

Back to the top
