MFC重绘控件

举个按钮简单重绘的例子。

头文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class CMyButton : public CButton
{
public:
	virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
};
 
class CMFCApplication1Dlg : public CDialogEx
{
	...
protected:
	virtual void DoDataExchange(CDataExchange* pDX);
	CMyButton m_myButton;
	...
};


CPP文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
void CMyButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	CDC *pDC = CDC::FromHandle(lpDrawItemStruct->hDC);
 
	pDC->Rectangle(&lpDrawItemStruct->rcItem);
 
	CString caption;
	if (lpDrawItemStruct->itemState & ODS_SELECTED)
	{
		caption = _T("down");
	}
	else
	{
		caption = _T("up");
	}
	pDC->ExtTextOut(0, 0, ETO_CLIPPED, &lpDrawItemStruct->rcItem, caption, NULL);
 
	CDC::DeleteTempMap();
}
 
void CMFCApplication1Dlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
 
	DDX_Control(pDX, IDC_BUTTON_MY, m_myButton);
}
 
BOOL CMFCApplication1Dlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();
	...
	m_myButton.ModifyStyle(0, BS_OWNERDRAW, 0);
	...
}