分类:
2008-10-13 16:48:41
设计XP风格的按钮
作者:
BOOL TrackMouseEvent( LPTRACKMOUSEEVENT lpEventTrack );参数:
void CButtonXp::OnMouseMove(UINT nFlags, CPoint point) { if(m_bOver ==FALSE) { //鼠标在按钮之上 m_bOver =TRUE; //按钮重绘 InvalidateRect(NULL,FALSE); //跟踪鼠标 //当鼠标离开按钮区域会收到WM_MOUSELEAVE,该消息直接调用OnMouseOut() TRACKMOUSEEVENT tme; tme.cbSize =sizeof(TRACKMOUSEEVENT); tme.dwFlags =TME_LEAVE; tme.dwHoverTime=0; tme.hwndTrack =m_hWnd; ::TrackMouseEvent(&tme); } CButton::OnMouseMove(nFlags, point); }再添加一成员函数OnMouseOut(),
在OnMouseOut()中写入以下代码
void CButtonXp::OnMouseOut () { //鼠标已离开按钮区域 m_bOver =FALSE; //重绘按钮 InvalidateRect(NULL,FALSE); }4、添加成员函数 MouseOver()
//返回鼠标是否在按钮区域内 BOOL CButtonXp::MouseOver() { return m_bOver; }5、最后重载DrawItem(LPDRAWITEMSTRUCT lpDIS)
void CButtonXp::DrawItem(LPDRAWITEMSTRUCT lpDIS) { CDC *pDC =CDC::FromHandle(lpDIS->hDC); CRect rtControl(lpDIS->rcItem); CPen pen,*old_pen; CBrush brush,*old_brush; CString strText; HFONT hOldFont = (HFONT)pDC->SelectObject ((HFONT)::GetStockObject (DEFAULT_GUI_FONT)); UINT state =lpDIS->itemState; if(state & ODS_FOCUS) { rtControl.DeflateRect(1,1); //拥有焦点矩形变小 } if((state & ODS_DISABLED) || (!MouseOver() &&!(state & ODS_SELECTED))) { //普通状态、禁用、拥有焦点三种情况下 pen.CreatePen (PS_SOLID, 1, ::GetSysColor(COLOR_3DSHADOW)); brush.CreateSolidBrush(HLS_TRANSFORM(::GetSysColor(COLOR_3DFACE),-10,0)); } else { COLORREF crBorder =::GetSysColor(COLOR_HIGHLIGHT); pen.CreatePen(PS_SOLID, 1, crBorder); if( state & ODS_SELECTED) { //按钮按下时 brush.CreateSolidBrush(HLS_TRANSFORM(crBorder,+50,-50)); pDC->SetTextColor(RGB(240,240,240)); } else { //鼠标在区域内 brush.CreateSolidBrush(HLS_TRANSFORM(crBorder,+80,-66)); pDC->SetTextColor(::GetSysColor(COLOR_BTNTEXT)); } } if(state &ODS_DISABLED) pDC->SetTextColor(::GetSysColor(COLOR_GRAYTEXT));//灰色字:禁用状态 else if(state & ODS_SELECTED) pDC->SetTextColor(RGB(240,240,240)); //白色字:PUSH状态 else if(MouseOver()) pDC->SetTextColor(0); //黑色字:热感应状态 else pDC->SetTextColor(::GetSysColor(COLOR_BTNTEXT)); //黑色字:普通状态 old_brush=pDC->SelectObject(&brush); old_pen =pDC->SelectObject(&pen); pDC->Rectangle(rtControl); pDC->SetBkMode(TRANSPARENT); GetWindowText(strText); pDC->DrawText(strText,rtControl,DT_SINGLELINE|DT_CENTER|DT_VCENTER); if(state & ODS_FOCUS) { rtControl.DeflateRect(3,3); pDC->DrawFocusRect(rtControl); } pDC->SelectObject(old_pen); pDC->SelectObject(old_brush); pDC->SelectObject(hOldFont); }还有一个要注意的是,要使用TrackMouseEvent(),必须在加入头文件winuser.h 和extern "C" WINUSERAPI BOOL WINAPI TrackMouseEvent(LPTRACKMOUSEEVENT lpEventTrack);