设计XP风格的按钮
2008-01-19 20:25:47 来源:WEB开发网核心提示:并在BEGIN_MESSAGE_MAP(CButtonXp, CButton)和END_MESSAGE_MAP()之间添加宏 ON_MESSAGE(WM_MOUSELEAVE,OnMouseOut)在OnMouseOut()中写入以下代码void CButtonXp::OnMouseOut (){//鼠标已离开按钮区域
并在BEGIN_MESSAGE_MAP(CButtonXp, CButton)和END_MESSAGE_MAP()之间添加
宏 ON_MESSAGE(WM_MOUSELEAVE,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);
本程序在win98 + Visual C++ 6.0环境下编译通过.
更多精彩
赞助商链接