MFC控制颜色

背景颜色输出
在OnPaint()函数实现控制 如:插入位图

     else

{
CRect rc;//定义对话框背景颜色
GetClientRect(&rc);
CPaintDC dc(this);
dc.FillSolidRect(&rc,RGB(0,0,0)); //可以实用COLORREF类型变量
CDialog::OnPaint();
}
控制子控件的颜色
1.在OnCtlColor方法中实现

     控制单个按钮语句为nIDctl==IDC_BUTTON
     为了调用绘制语句,可创建一个笔刷BRUSH m_brush
     在对话框类中设置画刷m_brush.CreateSolidBrush(RGB(2,34,43))
     再在此方法中返回此画刷即可,可用于绘制静态文本框背景颜色。
     添加pDC->SetBkMode(TRANSPARENT)可使文字无背景颜色。

2.建立一个继承类CTextBon重载其DrawItem虚函数实现按钮颜色按钮文字颜色的改变

     基类是CButton
     对话框中应包含此类的头文件
     重载DrawItem函数
     void CBOT::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) 

{
// TODO: Add your code to draw the specified item
//UINT uStyle =BS_DEFPUSHBUTTON;
UINT uStyle =DFCS_BUTTONPUSH;
ASSERT(lpDrawItemStruct->CtlType==ODT_BUTTON);
if (lpDrawItemStruct->itemState&ODS_SELECTED)
{
uStyle|=DFCS_PUSHED;
}
::DrawFrameControl(lpDrawItemStruct->hDC,&lpDrawItemStruct->rcItem,DFC_BUTTON,uStyle);
CDC *pDC=CDC::FromHandle(lpDrawItemStruct->hDC);
CString str;
GetWindowText(str);
CBrush B;
CRect rect;
CRect ftect;
ftect.CopyRect(&lpDrawItemStruct->rcItem);
DrawFocusRect(lpDrawItemStruct->hDC,(LPRECT)&ftect);
ftect.left+=4;
ftect.right-=4;
ftect.top+=4;
ftect.bottom-=4;

rect.CopyRect(&lpDrawItemStruct->rcItem);

pDC->Draw3dRect(rect,::GetSysColor(COLOR_BTNSHADOW),::GetSysColor(COLOR_BTNHILIGHT));
B.CreateSolidBrush(RGB(2,34,55));
::FillRect(lpDrawItemStruct->hDC,&rect,(HBRUSH)B.m_hObject);
::SetBkMode(lpDrawItemStruct->hDC,TRANSPARENT);
COLORREF col=::SetTextColor(lpDrawItemStruct->hDC,RGB(255,2,3));
::DrawText(lpDrawItemStruct->hDC,str,str.GetLength(),&lpDrawItemStruct->rcItem,DT_SINGLELINE|DT_VCENTER|DT_CENTER);
::SetTextColor(lpDrawItemStruct->hDC,col);

}

        把要改变的按钮勾选Owner Draw并关联一个CTextButton类的成员变量
        绘制对话框时程序即可调用
 缺点:无法自主控制,按钮无边框

3.响应MFC的OnDrawItem方法

        void CMyDlg::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct) 

{
// TODO: Add your message handler code here and/or call default
if(nIDCtl==IDC_BUTTON11)
{
CDC dc;
RECT rect;
dc.Attach(lpDrawItemStruct->hDC);
rect=lpDrawItemStruct->rcItem;
// dc.Draw3dRect(&rect,RGB(255,255,255),RGB(0,0,0));
dc.FillSolidRect(&rect,RGB(255,56,78)); //设置按钮背景色
UINT state=lpDrawItemStruct->itemState;
if(state&ODS_SELECTED)
{
dc.DrawEdge(&rect,EDGE_SUNKEN,BF_RECT);
}
else
{
dc.DrawEdge(&rect,EDGE_RAISED,BF_RECT); //绘制按钮边框
}
// dc.SetBkColor(RGB(100,100,23));
dc.SetTextColor(RGB(255,34,55)); //设置按钮文本颜色
TCHAR butter[MAX_PATH];
::GetWindowText(lpDrawItemStruct->hwndItem,butter,MAX_PATH);
dc.DrawText(butter,&rect,DT_CENTER|DT_VCENTER|DT_SINGLELINE);
dc.Detach();

}

CDialog::OnDrawItem(nIDCtl, lpDrawItemStruct);
}
按钮需勾选Owner Draw

   需注意:DrawItem与OnDrawItem同时存在时OnDrawItem方法无效,DrawItem调用后OnDrawItem无法再被调用。

如果想要了解更多,欢迎加入QQ群162876848,共同探讨吧

你可能感兴趣的:(MFC控制颜色)