我有一个CListCtrl类,我希望能够轻松地改变字体大小。我将CListCtrl子类化为MyListControl。我可以在PreSubclassWindow事件处理程序中使用此代码成功设置字体:
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)的方法,它只会改变现有的字体大小(保留face和其他特性)。所以我相信这种方法需要获取现有的字体,然后更改字体大小,但我尝试这样做的尝试失败了(这会导致我的程序失败):
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_);
}
如何创建此方法?
答案 0 :(得分:4)
我找到了一个有效的解决方案。我愿意接受改进建议:
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_);
}
实现这一目标的两个关键是:
font_.DeleteObject();
。显然,已经没有现有的字体对象。 MFC代码中有一些ASSERT用于检查现有指针。那个ASSERT导致我的代码失败。