信息: 更正 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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章