更多信息
应用程序可以删除只在特定的情况下一个 WM_SETFONT 消息中指定字体 ; 这些相同的限制将应用于 CFont 对象 SetFont() 调用中指定。
专门,请勿后已销毁控件将 CWnd 销毁指定的 CFont 对象之前。Windows 不会复制 SetFont() 调用中指定的字体。如果字体被销毁控件将被破坏之前,则会出现不可预知的结果。
例如对于应用程序用来更改的字体对话框使用 SetFont() 时, 应用程序应不销毁 CFont 对象,直到后它已破坏对话框。请在 CFont 对象而不是在类中函数之一进行字体局部变量的派生的对话框类的成员变量。这是最佳的方法,以确保对象存在对话框中的生存期内将 CFont。当应用程序将销毁对话框时,对话框框类析构函数将自动调用 CFont 析构函数删除字体句柄。
若要在对话框中指定的任何控件字体在最佳时间是在 OnInitDialog() 成员函数中。
下面的代码演示如何从 CModalDialog 派生对话框类和使用 SetFont() 成员函数:
示例代码
/* * Compiler options needed: None */ class CMyAboutBox : public CDialog { CFont m_font; public: // 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". //修正 lstrcpy(lf.lfFaceName,_T("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. GetDlgItem(IDC_TEXT1)->SetFont(&m_font); return TRUE; }