这两天需要给MFC中的EDIT框改变一下背景颜色,而且由于框比较多,且每次需要变色的框也是随机的,但是个数是确定的。在网上搜了好多,下面这个是介绍的比较清楚,而且可以用的一种方法。
由于本人用的vs2008,在对话框上右击没有添加事件处理函数一项,且对MFC也不是特别熟悉,所以开始只是在对话框类中重载了onctlcolor()函数,但添加时一直没有效果,最后发现出了只定义该函数外还需要在MAP中添加该函数的映射关系才能正常使用。另外要一次改变多个框的背景的话,需要开辟空间,先把这些框的ID存上,然后在onctlcolor()函数中一一比对。
MFC里画图了,颜色了的真抽象,没点基础好难理解啊,
转自:http://dendrites.blog.163.com/blog/static/165376178201010193214142/
这里介绍的改变文本编辑框的背景颜色的方法,不需要对CEdit生成新的类,步骤如下:
(1) 新建一个基于对话框的MFC应用程序,程序名称为Test
(2) 在对话框上添加两个文本框,ID分别为IDC_EDIT1和IDC_EDIT2
(3) 在CTestDlg的头文件中添加几个成员变量,如下所示:
view plainprint?
class CTestDlg : public CDialog
{
protected:
CBrush m_redbrush,m_bluebrush;
COLORREF m_redcolor,m_bluecolor,m_textcolor;
};
(4) 在CTestDlg.cpp文件的BOOL CTestDlg::OnInitDialog()中添加以下代码:
view plainprint?
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添加消息响应函数,编辑代码如下:
view plainprint?
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 静态文本