信息: 更正 SetFont() 函數,在 MFC 的使用 修改字體

概要
指定控件中的字體的 SetFont() 成員函數 CWnd 類的更改。在基於 Windows 的應用程序中正常工作的此函數,則必須確保後指定的控件已被破壞,SetFont() 調用中指定的 CFont 對象不銷燬直到。

Collapse image更多信息

在 SetFont() 接受一個 CFont 對象作爲參數 ; 該控件使用指定的字體來顯示其文本。若要將 WM_SETFONT 消息發送到該控件與對應於 CFont 對象字體句柄實現 SetFont() 函數。

應用程序可以刪除只在特定的情況下一個 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章