(1)新建一个基于对话框的MFC应用程序ColorDialogTest,删除对话框中原有控件。
(2)为类CColorDialogTestDlg添加成员变量:
COLORREF m_clr;
m_clr用来保存在颜色对话框上所选的颜色。
(3)切换到资源视图,在对话框上添加一个按钮“显示颜色对话框”,然后添加按钮事件处理代码如下:
void CColorDialogTestDlg::OnBnClickedButton1()
{
// TODO: 在此添加控件通知处理程序代码
CColorDialog dlg(0, CC_FULLOPEN, this);
if (IDOK == dlg.DoModal())
{
m_clr = dlg.GetColor();
Invalidate();
}
}
(4)在初始化函数CColorDialogTestDlg::OnInitDialog()的末尾添加m_clr的初始化代码:
m_clr = RGB(240,240,240);
在定位到类CColorDialogTestDlg的成员函数OnPaint()处,在else代码段内的CDialogEx::OnPaint();前添加设置背景色的代码:
else
{
CPaintDC dc(this);// 用于绘制的设备上下文
CBrush brush(m_clr);
CRect Rect;
GetClientRect(&Rect);
dc.FillRect(Rect, &brush);
CDialogEx::OnPaint();
}
(5)保存工程并运行,结果如图: