第一种方式:
(1)打开资源视图。
(2)双击打开STATIC所在的对话框
(3)修改STATIC的ID属性,这里假设为IDC_STATICMessage
(4) 为对话框添加类,假设为CxxxDialog
(5) 选择对话框,在属性面板上点击消息,并选择WM_CTLCOLOR
(6) 在对话框对应类的CPP中新增下面的代码
HBRUSH CxxxDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
//添加自己的代码
return hbr;
}
(7)在上面的代码中添加修改IDC_TEXT文本颜色的代码
HBRUSH CxxxDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); if (pWnd->GetDlgCtrlID() == IDC_STATICMessage) { pDC->SetTextColor(RGB(0, 0, 250)); }
return hbr; }
同样的方法可应用于修改字体
动态改变字体内容,使用
GetDlgItem(IDC_STATICMessage)->SetWindowText("I LOVE Chinese");
第二种方式:
在实际的应用中,可以用WM_CTLCOLOR 消息改变mfc中控件的颜色,比如现在就来改变一个static text控件的字体、字体大小、字体颜色和背景色
例如对话框的类中添加两个变量
方法:在classview选项卡中,选择CTestDlg,右键,add member variable
CBrush m_brush;
CFont m_font;
在OnInitDialog()函数中添加:
m_font.CreatePointFont(150,"华文行楷");//代表15号字体,华文行楷
m_brush.CreateSolidBrush(RGB(0,255,0));//画刷为绿色
2 添加WM_CTLCOLOR 消息响应,添加的方法为:
add windows message handler->WM_CTLCOLOR->add and edit
3 在HBRUSH CTestDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) 函数中的todo后添加代码,即:
HBRUSH CxxxDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
// TODO: Change any attributes of the DC here if (pWnd->GetDlgCtrlID() == IDC_STATICText) { pDC->SetBkColor(RGB(0,255,0));//背景色为绿色 pDC->SetTextColor(RGB(255, 0, 0));//文字为红色 pDC->SelectObject(&m_font);//文字为15号字体,华文行楷 return m_brush; } // TODO: Return a different brush if the default is not desired return hbr; }
这样就可以改变static text的背景色、字体、字体大小和字体颜色了。