MFC: Dynamically change control font size?

醉酒当歌 提交于 2020-03-01 02:34:05

问题


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_);
}

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_);

}

How can I create this method?


回答1:


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. 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.


来源:https://stackoverflow.com/questions/7617199/mfc-dynamically-change-control-font-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!