这里介绍的改变文本编辑框的背景颜色的方法,不需要对CEdit生成新的类,步骤如下:
(1) 新建一个基于对话框的MFC应用程序,程序名称为Test
(2) 在对话框上添加两个文本框,ID分别为IDC_EDIT1和IDC_EDIT2
(3) 在CTestDlg的头文件中添加几个成员变量,如下所示:
(4) 在CTestDlg.cpp文件的BOOL CTestDlg::OnInitDialog()中添加以下代码:
(5) 右击对话框空白面,选择Event,为WM_CTLCOLOR添加消息响应函数,编辑代码如下:
注:case的类别有以下几种:
CTLCOLOR_BTN 按钮控件
CTLCOLOR_DLG 对话框
CTLCOLOR_EDIT 编辑框
CTLCOLOR_LISTBOX 列表框
CTLCOLOR_MSGBOX 消息框
CTLCOLOR_SCROLLBAR 滚动条
CTLCOLOR_STATIC 静态文本
(1) 新建一个基于对话框的MFC应用程序,程序名称为Test
(2) 在对话框上添加两个文本框,ID分别为IDC_EDIT1和IDC_EDIT2
(3) 在CTestDlg的头文件中添加几个成员变量,如下所示:
- class CTestDlg : public CDialog
- {
- protected:
- CBrush m_redbrush,m_bluebrush;
- COLORREF m_redcolor,m_bluecolor,m_textcolor;
- };
(4) 在CTestDlg.cpp文件的BOOL CTestDlg::OnInitDialog()中添加以下代码:
- BOOL CTestDlg::OnInitDialog()
- {
- CDialog::OnInitDialog();
- // Set the icon for this dialog. The framework does this automatically
- // when the application's main window is not a dialog
- SetIcon(m_hIcon, TRUE); // Set big icon
- SetIcon(m_hIcon, FALSE); // Set small icon
- m_redcolor=RGB(255,0,0); // 红色
- m_bluecolor=RGB(0,0,255); // 蓝色
- m_textcolor=RGB(255,255,255); // 文本颜色设置为白色
- m_redbrush.CreateSolidBrush(m_redcolor); // 红色背景色
- m_bluebrush.CreateSolidBrush(m_bluecolor); // 蓝色背景色
- return TRUE; // return TRUE unless you set the focus to a control
- }
(5) 右击对话框空白面,选择Event,为WM_CTLCOLOR添加消息响应函数,编辑代码如下:
- HBRUSH CTestDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
- {
- HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
- // TODO: Change any attributes of the DC here
- switch (nCtlColor) //对所有同一类型的控件进行判断
- {
- // process my edit controls by ID.
- case CTLCOLOR_EDIT:
- case CTLCOLOR_MSGBOX://假设控件是文本框或者消息框,则进入下一个switch
- switch (pWnd->GetDlgCtrlID())//对某一个特定控件进行判断
- {
- // first CEdit control ID
- case IDC_EDIT1: // 第一个文本框
- // here
- pDC->SetBkColor(m_bluecolor); // change the background
- // color [background colour
- // of the text ONLY]
- pDC->SetTextColor(m_textcolor); // change the text color
- hbr = (HBRUSH) m_bluebrush; // apply the blue brush
- // [this fills the control
- // rectangle]
- break;
- // second CEdit control ID
- case IDC_EDIT2: // 第二个文本框
- // but control is still
- // filled with the brush
- // color!
- pDC->SetBkMode(TRANSPARENT); // make background
- // transparent [only affects
- // the TEXT itself]
- pDC->SetTextColor(m_textcolor); // change the text color
- hbr = (HBRUSH) m_redbrush; // apply the red brush
- // [this fills the control
- // rectangle]
- break;
- default:
- hbr=CDialog::OnCtlColor(pDC,pWnd,nCtlColor);
- break;
- }
- break;
- }
- // TODO: Return a different brush if the default is not desired
- return hbr;
- }
注:case的类别有以下几种:
CTLCOLOR_BTN 按钮控件
CTLCOLOR_DLG 对话框
CTLCOLOR_EDIT 编辑框
CTLCOLOR_LISTBOX 列表框
CTLCOLOR_MSGBOX 消息框
CTLCOLOR_SCROLLBAR 滚动条
CTLCOLOR_STATIC 静态文本