www.gusucode.com > VC++自绘按钮精彩实例-源码程序 > VC++自绘按钮精彩实例-源码程序/code/源代码/MyColorButton.cpp

    // MyColorButton.cpp : implementation file
// Download by http://www.NewXing.com
#include "stdafx.h"
#include "test4.h"
#include "MyColorButton.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CMyColorButton

CMyColorButton::CMyColorButton()
{
	m_ButtonBit[0].LoadBitmap(IDB_BITMAP1);
	m_ButtonBit[1].LoadBitmap(IDB_BITMAP2);
	m_ButtonBit[2].LoadBitmap(IDB_BITMAP3);
	m_ButtonBit[3].LoadBitmap(IDB_BITMAP4);
	m_ButtonBit[4].LoadBitmap(IDB_BITMAP5);
	m_Tracking=FALSE;

}

CMyColorButton::~CMyColorButton()
{
}


BEGIN_MESSAGE_MAP(CMyColorButton, CButton)
	//{{AFX_MSG_MAP(CMyColorButton)
	ON_WM_MOUSEMOVE()
	ON_MESSAGE(WM_MOUSEHOVER,OnMouseHover)
	ON_MESSAGE(WM_MOUSELEAVE,OnMouseLeave)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CMyColorButton message handlers

void CMyColorButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) 
{
	int nIndex=0;//默认状态下
  	CDC *pDC=CDC::FromHandle(lpDrawItemStruct->hDC);
   
	UINT nState=lpDrawItemStruct->itemState;
    if (m_Tracking)
    {
		if (nState&ODS_SELECTED)
		{
			nIndex=2;//鼠标经过
		}
		else
		{
			nIndex=4;//鼠标按下
		}
    }
	else if (nState&ODS_FOCUS)
	{
	nIndex=3;//焦点下
	}
	else if (nState&ODS_DISABLED)
	{
		nIndex=1;//不可用
	}

DrawButton(pDC,nIndex);
	
}

void CMyColorButton::DrawButton(CDC *pDC, int nIndex)
{


	CRect rect;
	GetClientRect(&rect);
	CDC MemDC;
	MemDC.CreateCompatibleDC(pDC);

	MemDC.SelectObject(m_ButtonBit[nIndex]);
	CBitmap *pOldBmp = MemDC.SelectObject(&m_ButtonBit[nIndex]);
	pDC->BitBlt(0, 0, rect.Width(), rect.Height(), &MemDC, 0, 0, SRCCOPY);

	////////////////////////////设置文本及文本颜色
	
	CString strText;
	GetWindowText(strText);
	HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
	CFont *pFont = CFont::FromHandle(hFont);
	CFont *pOldFont = (CFont*)MemDC.SelectObject(pFont);
	pDC->SetBkMode(TRANSPARENT);
	pDC->DrawText(strText, rect, DT_CENTER|DT_VCENTER|DT_SINGLELINE);
	
	MemDC.SelectObject(pOldBmp);
	pDC->SelectObject(pOldFont);
}

void CMyColorButton::OnMouseMove(UINT nFlags, CPoint point) 
{
	if (!m_Tracking)
	{
		TRACKMOUSEEVENT tme;
		tme.cbSize=sizeof(tme);
		tme.dwFlags=TME_HOVER|TME_LEAVE;
		tme.hwndTrack=m_hWnd;
		tme.dwHoverTime=1;
		m_Tracking=_TrackMouseEvent(&tme);
	}
	
	CButton::OnMouseMove(nFlags, point);
}
LRESULT CMyColorButton::OnMouseLeave(WPARAM wParam,LPARAM lParam)
{
	m_Tracking=FALSE;
	RedrawWindow();
	return 0L;
}
LRESULT CMyColorButton::OnMouseHover(WPARAM wParam,LPARAM lParam)
{
   
	RedrawWindow();
	return 0L;
}