MFC 按钮如何改变颜色
我们发现想改变对话框的背景颜色是很简单的,但是对话框的背景颜色改变了后,我们发现按钮的颜色没有改变,如下图。
这样做出来的对话框看起来,不是很自然,我们也想把按钮的颜色改变一下。这就用到了按钮的重绘。
按钮的重绘,主要原理是:一把按钮的重绘属性激活,而覆写DrawItem方法。
新建一个MFC类CCustButton类,继承CButton类。
主要代码如下:CustomButton.h
class CCustomButton : public CButton { DECLARE_DYNAMIC(CCustomButton) public: CCustomButton(); virtual ~CCustomButton(); void SetButtonBgColor(COLORREF color); void SetButtonTextColor(COLORREF color); private: COLORREF m_bgColor; COLORREF m_textColor; BOOL m_bPressed; protected: DECLARE_MESSAGE_MAP() afx_msg void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); }; //CustomButton .cpp IMPLEMENT_DYNAMIC(CCustomButton, CButton) CCustomButton::CCustomButton() { m_bgColor = RGB(239, 233, 235); m_textColor = RGB(0, 0, 0); m_bPressed = FALSE; } CCustomButton::~CCustomButton() { } BEGIN_MESSAGE_MAP(CCustomButton, CButton) ON_WM_DRAWITEM() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() END_MESSAGE_MAP() // CCustomButton 消息处理程序 void CCustomButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { CRect rect; GetClientRect(rect); CDC dc; dc.Attach(lpDrawItemStruct->hDC); UINT state = lpDrawItemStruct->itemState; CRect focusRect(rect); focusRect.DeflateRect(4, 4, 4, 4); if ((state & ODS_SELECTED) || (state & ODS_FOCUS)) { CPen pen(PS_DASHDOTDOT, 1, RGB(0, 0, 0)); CBrush brush; brush.CreateStockObject(NULL_BRUSH); dc.SelectObject(&brush); dc.SelectObject(&pen); dc.FillSolidRect(rect,m_bgColor); dc.DrawFocusRect(focusRect); dc.Draw3dRect(rect, RGB(51, 51, 51), RGB(0, 0, 0)); } else { CPen pen(PS_DOT, 1, m_bgColor); CBrush brush; brush.CreateStockObject(NULL_BRUSH); dc.SelectObject(&brush); dc.SelectObject(&pen); dc.FillSolidRect(rect, m_bgColor); dc.Rectangle(focusRect); } dc.DrawEdge(rect, BDR_RAISEDINNER | BDR_RAISEDOUTER, BF_BOTTOMLEFT | BF_TOPRIGHT); if (m_bPressed) { dc.DrawFocusRect(focusRect); dc.DrawEdge(rect, BDR_RAISEDINNER | BDR_SUNKENOUTER, BF_BOTTOMLEFT | BF_TOPRIGHT); dc.Draw3dRect(rect, RGB(51, 51, 51), RGB(0, 0, 0)); } CString strText; GetWindowText(strText); dc.SetBkMode(TRANSPARENT); dc.SetTextColor(m_textColor); if (state & ODS_DISABLED) { dc.SetTextColor(RGB(172, 168, 153)); } dc.DrawText(strText, rect, DT_CENTER | DT_SINGLELINE | DT_VCENTER); dc.Detach(); } //按钮被按下 void CCustomButton::OnLButtonDown(UINT nFlags, CPoint point) { m_bPressed = TRUE; CButton::OnLButtonDown(nFlags, point); } //按钮被释放 void CCustomButton::OnLButtonUp(UINT nFlags, CPoint point) { m_bPressed = FALSE; CButton::OnLButtonDown(nFlags, point); } //设置按钮背景的颜色 void CCustomButton::SetButtonBgColor(COLORREF color) { m_bgColor = color; } //设置按钮字体的颜色 void CCustomButton::SetButtonTextColor(COLORREF color) { m_textColor = color; }
将按钮的自绘属性设为true
给按钮添加一个变量
CButton m_bt_OpenFile;
将CButton改成CCustomButton 变成
CCustomButton m_bt_OpenFile;
在dialog里调用
//设置按钮背景色
m_bt_OpenFile.SetButtonBgColor(m_BgColor);
//刷新窗口
InvalidateRect(NULL, TRUE);
UpdateWindow();即可
m_BgColor 为对话框的背景色。
效果如下:
高山流水,海纳百川!