MFC: dynamically change control font size?

I have a CListCtrl class that I would like to easily change the font size. I have subclassed CListCtrl as MyListControl. I can successfully install 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_); } 

It works. However, I would like to create a SetFontSize (int size) method that simply changes the existing font size (leaving the face and other characteristics as they are). Therefore, I believe that this method will have 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?

+4
source share
1 answer

I found a working solution. I am 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_); } 

Two keys to make this work:

  • Delete a copy of LOGFONT, lfNew.
  • Call font_.DeleteObject(); before creating a new font. Apparently, an existing font object can no longer exist. There is some ASSERT in the MFC code that checks for an existing pointer. This ASSERT is the reason that my code fails.
+3
source

All Articles