我有一个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_);
}
Run Code Online (Sandbox Code Playgroud)
这可行。但是,我想做的是创建一个名为SetFontSize(int size)的方法,该方法将简单地更改现有的字体大小(不改变外观和其他特征)。因此,我认为此方法将需要获取现有字体,然后更改字体大小,但是我这样做的尝试失败了(这杀死了我的程序):
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_);
}
Run Code Online (Sandbox Code Playgroud)
如何创建此方法?
我找到了一个可行的解决方案。我愿意接受改进建议:
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_);
}
Run Code Online (Sandbox Code Playgroud)
使其发挥作用的两个关键是:
font_.DeleteObject();在创建新字体之前调用。显然已经不可能有一个现有的字体对象。MFC 代码中有一些 ASSERT 检查现有指针。ASSERT 是导致我的代码失败的原因。| 归档时间: |
|
| 查看次数: |
12015 次 |
| 最近记录: |