在实际的应用中,可以用WM_CTLCOLOR 消息改变mfc中控件的颜色,比如现在就来改变一个static text的背景色和字体:
1. 在对话框的类中添加两个变量:
CBrush m_brush;
CFont m_font;
在OnInitDialog()函数中添加:
// TODO: 在此添加额外的初始化代码
m_font.CreatePointFont(150,"华文行楷");
m_brush.CreateSolidBrush(#00ff00);
2. 添加WM_CTLCOLOR 消息响应,添加的方法为:
在对话框类中声明:afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) ;
在消息映射中添加: ON_WM_CTLCOLOR()
如:
BEGIN_MESSAGE_MAP(CtestEnvDlg, CDialog)
ON_WM_CTLCOLOR()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
3. 添加响应函数:
HBRUSH CYourDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
if(m_yourStatic.m_hWnd == pWnd->m_hWnd)
{
pDC->SetBkColor(#00ff00);
//pDC->SetTextColor(#ff0000);//文字色
pDC->SelectObject(&m_font);
return m_brush;
}
return hbr;
} HBRUSH CJuanZongAJAddCriminal::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
// TODO: 在此更改 DC 的任何属性
if (pWnd->GetDlgCtrlID() == IDC_STATIC)
{
//pDC->SetBkMode(TRANSPARENT);
pDC->SetTextColor(#dedede);
pDC->SetBkColor(#383838);
hbr = CreateSolidBrush(#383838);
}
if (nCtlColor == CTLCOLOR_EDIT)
{
pDC->SetTextColor(#dedede);
pDC->SetBkColor(#14344d);
hbr = CreateSolidBrush(#14344d);
}
// TODO: 如果默认的不是所需画笔,则返回另一个画笔
return hbr;
}
这样就可以改变static text的颜色和字体了