在 MFC 中的 SetFont() 函数的正确使用

概要

CWnd 类的 SetFont() 成员函数更改中指定控件的字体。 此函数在基于 Windows 的应用程序中正常工作,必须确保指定的控件已被销毁之后,SetFont() 调用中指定的 CFont 对象不销毁之前。

更多信息

SetFont() 接受 CFont 对象作为参数。 控件使用指定的字体来显示其文本。 SetFont() 函数实现将 WM_SETFONT 消息发送到具有与 CFont 对象相对应的字体句柄的控件。

应用程序可以删除只在某些情况下 ; WM_SETFONT 消息中指定的字体 这些限制同样适用于 SetFont() 调用中指定的 CFont 对象。

具体来说,请勿在控件已被破坏的 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".
   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;
}

转自:http://support.microsoft.com/kb/85518

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值