怎么用MFC自绘按钮
1个回答
展开全部
新建一个MFC类CCustButton类,继承CButton类。
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);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询