更多信息
應用程序可以刪除只在特定的情況下一個 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; }