改变对话框中的CEdit控件的背景色

来源:互联网 发布:macbook pro必备软件 编辑:程序博客网 时间:2024/04/30 21:07

下面的例子将改变指定的CEdit控件的背景色,每一个CEdit控件都可以使用不同的颜色。在例子中我使用了蓝色和红色的背景色和白色的文字颜色。
CTestDlg的头文件中,声明CBrushCOLOREF的成员变量:
class CTestDlg : public CDialog
{
protected:
CBrush m_redbrush,m_bluebrush;
COLORREF m_redcolor,m_bluecolor,m_textcolor;
};
然后加下面的几行在OnInitDialog中:
BOOL CTestDlg::OnInitDialog()
{
m_redcolor=RGB(255,0,0);
// red

m_bluecolor=RGB(0,0,255); // blue
m_textcolor=RGB(255,255,255); // white text
m_redbrush.CreateSolidBrush(m_redcolor); // red background
m_bluebrush.CreateSolidBrush(m_bluecolor); // blue background
}
最后在OnCtlColor中加入:
HBRUSH CTestDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr;
switch (nCtlColor)
{
case CTLCOLOR_EDIT:
case CTLCOLOR_MSGBOX:
switch (pWnd->GetDlgCtrlID())
{
case IDC_MYCONTROLNAME1:
// first CEdit control ID
// put your own CONTROL ID here

pDC->SetBkColor(bluecolor); // change the background color
pDC->SetTextColor(textcolor); // change the text color
hbr = (HBRUSH) m_bluebrush; // apply the brush
break;
case IDC_MYCONTROLNAME2:
// second CEdit control ID
// put your own CONTROL ID here

pDC->SetBkColor(redcolor); // change the background color
pDC->SetTextColor(textcolor); // change the text color
hbr = (HBRUSH) m_redbrush; // apply the brush
break;
// otherwise do default handling of OnCtlColor

default:
hbr=CDialog::OnCtlColor(pDC,pWnd,nCtlColor);
break;
}
break;
// otherwise do default handling of OnCtlColor

default:
hbr=CDialog::OnCtlColor(pDC,pWnd,nCtlColor);
}
return hbr; // return brush
}