MFC中CMFCColorButton是Visual Studio 2008 SP1版本或更高版本才提供的,用来对颜色的选取采集
下面介绍一下,CMFCColorButton的使用方法
1.新建对话框的工程,名称为MyColorButtonDemo
2.对话框上添加一个按钮,并将按钮绑定变量类型为CMFCColorButton,变量名为m_ColorPicker
3.为按钮添加相关事件
C/C++ Code复制内容到剪贴板
voidCMyColorButtonDemoDlg::OnBnClickedButton1()
{
COLORREFcolor = m_ColorPicker.GetColor();
if(color == -1)
{
color = m_ColorPicker.GetAutomaticColor();
}
}
4.在对话框的OnInitDialog() 函数里面添加以下代码:
C/C++ Code复制内容到剪贴板
BOOLCMyColorButtonDemoDlg::OnInitDialog()
{
CDialog::OnInitDialog();
//中间省略·····
m_ColorPicker.EnableAutomaticButton(_T("默认值"), RGB(0, 0, 0));
m_ColorPicker.EnableOtherButton(_T("其余颜色"));
m_ColorPicker.SetColor((COLORREF)-1);
m_ColorPicker.SetColumnsNumber(10);
returnTRUE;// 除非将焦点设置到控件,否则返回 TRUE
}
.在新建工程时,都有一个InitInstance函数的,找到这个函数添加如下代码
不添加下面的代码其实编译运行就可以看到效果了,但是没有应用系统主题
C/C++ Code复制内容到剪贴板
BOOLCMyColorButtonDemoApp::InitInstance()
{
//·····
SetRegistryKey(_T("应用程序向导生成的本地应用程序"));
CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); //这一句
CMyColorButtonDemoDlg dlg;
//····
}
运行效果图
如果要改造这个按钮,比如右边的三角下拉不是很好看,要改动话就要派生自CMFCColorButton来重写OnDraw函数,在这里我要去掉右边的三角下拉,还有去掉
那默认值的文本。重载之后的OnDraw函数如下:
C/C++ Code复制内容到剪贴板
voidCSkinColorButton::OnDraw(CDC* pDC,constCRect& rect,UINTuiState)
{
ASSERT_VALID(pDC);
if(m_pPalette == NULL)
{
RebuildPalette(NULL);
}
CPalette* pCurPalette = pDC->SelectPalette(m_pPalette, FALSE);
pDC->RealizePalette();
CSize sizeArrow = CMenuImages::Size();
CRect rectColor = rect;
COLORREFcolor = m_Color;
if(color == (COLORREF) -1)// Automatic
{
//---------------------------
// Draw automatic text label:
//---------------------------
color = m_ColorAutomatic;
}
//----------------
// Draw color box:
//----------------
rectColor.DeflateRect(2, 2);
pDC->Draw3dRect(rectColor, afxGlobalData.clrBtnHilite, afxGlobalData.clrBtnHilite);
rectColor.DeflateRect(1, 1);
pDC->Draw3dRect(rectColor, afxGlobalData.clrBtnDkShadow, afxGlobalData.clrBtnDkShadow);
rectColor.DeflateRect(1, 1);
if(color != (COLORREF)-1 &&(uiState & ODS_DISABLED) == 0)
{
if(afxGlobalData.m_nBitsPerPixel == 8)// 256 colors
{
ASSERT_VALID(m_pPalette);
color = PALETTEINDEX(m_pPalette->GetNearestPaletteIndex(color));
}
CBrush br(color);
pDC->FillRect(rectColor, &br);
}
if(pCurPalette != NULL)
{
pDC->SelectPalette(pCurPalette, FALSE);
}
}
还有重载OnDrawFocusRect函数,这是获得焦点时的矩形,重载后如下
C/C++ Code复制内容到剪贴板
voidCSkinColorButton::OnDrawFocusRect(CDC* pDC,constCRect& rectClient)
{
CSize sizeArrow = CMenuImages::Size();
CRect rectColor = rectClient;
CMFCButton::OnDrawFocusRect(pDC, rectColor);
}
重绘后的效果图
参考资料http://msdn.microsoft.com/en-us/library/bb983854.aspx