MFC:动态更改控件的字体大小吗? [英] MFC: Dynamically change control font size?

查看:475
本文介绍了MFC:动态更改控件的字体大小吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CListCtrl类,我希望能够轻松更改其字体大小.我将CListCtrl子类化为MyListControl.我可以在PreSubclassWindow事件处理程序中使用以下代码成功设置字体:

I have a CListCtrl class that I'd like to be able to easily change the font size of. I subclassed the CListCtrl as MyListControl. I can successfully set the font using this code in the PreSubclassWindow event handler:

void MyListControl::PreSubclassWindow()
{
    CListCtrl::PreSubclassWindow();

    // from http://support.microsoft.com/kb/85518
    LOGFONT lf;                        // Used to create the CFont.

    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".
    font_.CreateFontIndirect(&lf);    // Create the font.
    // Use the font to paint a control.
    SetFont(&font_);
}

这有效.但是,我想做的是创建一个名为SetFontSize(int size)的方法,该方法将简单地更改现有的字体大小(不改变外观和其他特征).因此,我认为该方法需要获取现有字体,然后更改字体大小,但是我这样做的尝试失败了(这杀死了我的程序):

This works. However, what I'd like to do is create a method called SetFontSize(int size) which will simply change the existing font size (leaving the face and other characteristics as is). So I believe this method would need to get the existing font and then change the font size but my attempts to do this have failed (this kills my program):

void MyListControl::SetFontSize(int pixelHeight)
{
    LOGFONT lf;                        // Used to create the CFont.

    CFont *currentFont = GetFont();
    currentFont->GetLogFont(&lf);
    LOGFONT lfNew = lf;
    lfNew.lfHeight = pixelHeight;                  // Request a 20-pixel-high font
    font_.CreateFontIndirect(&lf);    // Create the font.

    // Use the font to paint a control.
    SetFont(&font_);

}

如何创建此方法?

推荐答案

我找到了可行的解决方案.我愿意提出改进建议:

I found a working solution. I'm open to suggestions for improvement:

void MyListControl::SetFontSize(int pixelHeight)
{
    // from http://support.microsoft.com/kb/85518
    LOGFONT lf;                        // Used to create the CFont.

    CFont *currentFont = GetFont();
    currentFont->GetLogFont(&lf);
    lf.lfHeight = pixelHeight;
    font_.DeleteObject();
    font_.CreateFontIndirect(&lf);    // Create the font.

    // Use the font to paint a control.
    SetFont(&font_);
}

使此功能生效的两个关键是:

The two keys to getting this to work were:

  1. 删除LOGFONT的副本lfNew.
  2. 在创建新字体之前调用font_.DeleteObject();.显然尚不存在现有的字体对象. MFC代码中有一些ASSERT,用于检查现有的指针.那个ASSERT导致我的代码失败.
  1. Removing the copy of the LOGFONT, lfNew.
  2. Calling font_.DeleteObject(); before creating a new font. Apparently there can't be an existing font object already. There is some ASSERT in the MFC code that checks for an existing pointer. That ASSERT is what was causing my code to fail.

这篇关于MFC:动态更改控件的字体大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆