mfc 绘制 圆形按钮 继承CButton

头文件

// MyButton 圆形按钮

class MyButton : public CButton
{
private:
	bool is_pressed;  //鼠标是否按下
public:
	virtual void PreSubclassWindow();  //修改自绘属性
	virtual void DrawItem(LPDRAWITEMSTRUCT /*lpDrawItemStruct*/);  //绘制 圆形按钮
public:
	DECLARE_MESSAGE_MAP()
	afx_msg void OnLButtonDown(UINT nFlags, CPoint point);  //鼠标按下
	afx_msg void OnLButtonUp(UINT nFlags, CPoint point);  //鼠标松开
	afx_msg BOOL OnEraseBkgnd(CDC* pDC);  //不擦除背景
};

实现文件

// MyButton

void MyButton::PreSubclassWindow()
{
	ModifyStyle(0,BS_OWNERDRAW);
	is_pressed = false;
	CButton::PreSubclassWindow();
}

void MyButton::DrawItem(LPDRAWITEMSTRUCT lp)
{
	CRect rc = lp->rcItem;
	CDC dc;
	dc.Attach(lp->hDC);
	dc.SetBkMode(TRANSPARENT);
	CBrush br;
	br.CreateStockObject(NULL_BRUSH);
	dc.SelectObject(&br);
	if (is_pressed)
	{
		CPen pen(PS_SOLID,2,RGB(255,0,0));
		dc.SelectObject(&pen);
		dc.Ellipse(0,0,rc.Width(),rc.Height());
		dc.SetTextColor(RGB(255,0,0));
	}
	else
	{
		CPen pen(PS_SOLID,2,RGB(0,255,0));
		dc.SelectObject(&pen);
		dc.Ellipse(0,0,rc.Width(),rc.Height());
		dc.SetTextColor(RGB(0,255,0));
	}
	CString str;
	GetWindowText(str);
	dc.DrawText(str,CRect(0,0,rc.right,rc.bottom),DT_CENTER | DT_VCENTER | DT_SINGLELINE);
	dc.DeleteDC();
}

BEGIN_MESSAGE_MAP(MyButton, CButton)
	ON_WM_LBUTTONDOWN()
	ON_WM_LBUTTONUP()
	ON_WM_ERASEBKGND()
END_MESSAGE_MAP()


void MyButton::OnLButtonDown(UINT nFlags, CPoint point)
{
	is_pressed = true;
	CButton::OnLButtonDown(nFlags, point);
}

void MyButton::OnLButtonUp(UINT nFlags, CPoint point)
{
	is_pressed = false;
	CButton::OnLButtonUp(nFlags, point);
}

BOOL MyButton::OnEraseBkgnd(CDC* pDC)
{
	return TRUE;  //不擦除背景
}

为 按钮 关联 控件变量,在.h文件中将按钮类型改为MyButton即可。
展开阅读全文

没有更多推荐了,返回首页