为什么 CFont font1 放在函数里面不能改变字体大小?
如下面的代码:
若CFont font1 放在 OnInitDialog() 里面,字体的大小就不能改变,若放在 OnInitDialog()
的外面字体大小就可以改变.
BOOL CAboutDlg::OnInitDialog()
{
CDialog::OnInitDialog();
CFont font1; // 放在这字体的大小是不能改变的
font1.CreateFont(
30, // nHeight
0, // nWidth
0, // nEscapement
0, // nOrientation
FW_NORMAL, // nWeight
TRUE, // bItalic
TRUE, // bUnderline
0, // cStrikeOut
ANSI_CHARSET, // nCharSet
OUT_DEFAULT_PRECIS, // nOutPrecision
CLIP_DEFAULT_PRECIS, // nClipPrecision
DEFAULT_QUALITY, // nQuality
DEFAULT_PITCH | FF_SWISS, // nPitchAndFamily
_T("Arial")); // lpszFacename
GetDlgItem(IDC_STATIC1)->SetFont(&font1);
}
[解决办法]
CFont font1在执行完OnInitDialog函数时析构了。
[解决办法]
The SetFont() accepts a CFont object as a parameter; the control uses the specified font to display its text. The SetFont() function is implemented to send a WM_SETFONT message to the control with the font handle that corresponds to the CFont object.
An application can delete the font specified in a WM_SETFONT message only under certain circumstances; these same restrictions apply to the CFont object specified in a SetFont() call.
Specifically, do not destroy the specified CFont object until after the CWnd control has been destroyed. Windows does not copy the font specified in a SetFont() call. If the font is destroyed before the control is destroyed, unpredictable results can occur.
For example, when an application uses SetFont() to change the font a dialog box uses, the application should not destroy the CFont object until after it has destroyed the dialog box. Make the CFont object a member variable of the derived dialog box class instead of making the font a local variable in one of the functions in the class. This is the best method to ensure that the CFont object exists for the lifetime of the dialog box. When the application destroys the dialog box, the dialog box class destructor automatically calls the CFont destructor to delete the font handle.
CFont font不要用函数的局部变量,定义为对话框类的成员变量或静态变量或全局变量。