第一种办法(应该是最好的办法,可以正对单个控件来修改颜色,也许对其他类型的控件也可通用):
首先我们在对话框中添加OnCtlColor消息映射函数,函数作用/函数原型/参数解释请看MSDN描述~
QUOTE:
CWnd::OnCtlColor See Also然后我们在对话框上放置两个STATIC控件,ID分别为:IDC_STCCOLOR和IDC_STCTWO。然后在对话框的类中添加成员变量(别告诉我你不知道怎么添加……),变量需要两个,每个成员变量对应一个控件~
CWnd Overview | Class Members | Hierarchy Chart | CDC::SetBkColor
The framework calls this member function when a child control is about to be drawn.
afx_msg HBRUSH OnCtlColor(
CDC* pDC,
CWnd* pWnd,
UINT nCtlColor
);
Parameters
pDC
Contains a pointer to the display context for the child window. May be temporary.
pWnd
Contains a pointer to the control asking for the color. May be temporary.
nCtlColor
Contains one of the following values, specifying the type of control:
CTLCOLOR_BTN Button control
CTLCOLOR_DLG Dialog box
CTLCOLOR_EDIT Edit control
CTLCOLOR_LISTBOX List-box control
CTLCOLOR_MSGBOX Message box
CTLCOLOR_SCROLLBAR Scroll-bar control
CTLCOLOR_STATIC Static control
Return Value
OnCtlColor must return a handle to the brush that is to be used for painting the control background.
QUOTE:
HBRUSH CMFCDialogDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)这里之所以要先判断句柄,是因为我们要针对某一个控件进行设置。如果你直接使用pDC->SetTextColor来设置,那么MFC会遍历窗体的所有控件,然后把颜色设置成一样。
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
if (GetDlgItem(IDC_STCCOLOR) == pWnd)
{
pDC->SetTextColor(#ff0000);
}
else if (GetDlgItem(IDC_STCTWO) == pWnd)
{
pDC->SetTextColor(#0000ff);
}
return hbr;
}
QUOTE:
void CMFCDialogDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_STCCOLOR, m_cstcColor);
DDX_Control(pDX, IDC_STCTWO, m_cstcTwo);
}
第二种办法:
在实际的应用中,可以用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->SelectObject(&m_font);
return m_brush;
}
return hbr;
}
这样就可以改变static text的颜色和字体了