前几天因项目需要动态创建文本编辑框,但是发现new出来的文本编辑框字体是默认黑体加粗的 与整体不协调,查了好多资料终于搞定:如下:
一、创建新类CMyEdit继承自CEdit
添加消息:ON_WM_CTLCOLOR()
afx_msg HBRUSH CtlColor(CDC* pDC, UINT nCtlColor);
HBRUSH CMyEdit::CtlColor(CDC* pDC, UINT nCtlColor)
{
// TODO: Change any attributes of the DC here
pDC->SetTextColor(RGB(0,0,255)); //设置字体颜色
pDC->SelectObject(m_pFont); //设置字体样式
// TODO: Return a non-NULL brush if the parent's handler should not be called
return NULL;
}
需要注意的是,在类向导中找到 =WM_CTLCOLOR,而不是 WM_CTLCOLOR
字体设置:
CFont* m_pFont;
可以在构造函数中设置为默认值:
m_pFont = new CFont();
m_pFont->CreateFont( 13, //nHeight
0, //nWidth
0, //nEscapement
0, //nOrientation
FW_NORMAL, //nWeight
FALSE, //bItalic
FALSE, //bUnderline
0, //cStrikeOut
ANSI_CHARSET, //nCharSet
OUT_DEFAULT_PRECIS, //nOutPrecision
CLIP_DEFAULT_PRECIS, //nClipPrecision
DEFAULT_QUALITY, //nQuality
DEFAULT_PITCH | FF_SWISS, //nPitchAndFamily
_T("宋体"));
也可以做个函数自行设置:
//设置字体
void CMyEdit::SetTextFont(int FontHight,LPCTSTR FontName)
{
if (m_pFont)
{
delete m_pFont;
m_pFont = NULL;
LOGFONT logFont;
m_pFont = new CFont();
m_pFont->CreateFont( FontHight, //nHeight
0, //nWidth
0, //nEscapement
0, //nOrientation
FW_NORMAL, //nWeight
FALSE, //bItalic
FALSE, //bUnderline
0, //cStrikeOut
ANSI_CHARSET, //nCharSet
OUT_DEFAULT_PRECIS, //nOutPrecision
CLIP_DEFAULT_PRECIS, //nClipPrecision
DEFAULT_QUALITY, //nQuality
DEFAULT_PITCH | FF_SWISS, //nPitchAndFamily
FontName);
}
三、详细代码可到下面的链接下载