INFO: Correct Use of the SetFont() Function in MFC

만료된 KB 콘텐츠 고지 사항

이 문서는 Microsoft에서 더 이상 지원하지 않는 제품에 대해 작성되었습니다. 따라서 이 문서는 “있는 그대로" 제공되며 더 이상 업데이트되지 않습니다.


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 Code

* Compiler options needed: None

class CMyAboutBox : public CDialog
CFont m_font;

// Constructor -- This code assumes a dialog box
// template named "ABOUTDLG" in the application's .RC file.

CMyAboutBox(CWnd* pParentWnd = NULL) :
CModalDialog("ABOUTDLG", pParentWnd) {};

BOOL OnInitDialog();

// OnInitDialog() function -- Called after Windows creates
// the dialog box but before it is painted on the screen.

BOOL CMyAboutBox::OnInitDialog()
LOGFONT lf; // Used to create the CFont.

CDialog::OnInitDialog(); // Call default ::OnInitDialog

memset(&lf, 0, sizeof(LOGFONT)); // Clear out structure.
lf.lfHeight = 20; // Request a 20-pixel-high font
strcpy(lf.lfFaceName, "Arial"); // with face name "Arial".
m_font.CreateFontIndirect(&lf); // Create the font.

// Use the font to paint a control. This code assumes
// a control named IDC_TEXT1 in the dialog box.

return TRUE;

문서 ID: 85518 - 마지막 검토: 2006. 11. 21. - 수정: 1