自绘按钮类
RoundButton.h
#pragma once #include "afxwin.h" class CRoundButton : public CButton { public: CRoundButton(void); ~CRoundButton(void); virtual void DrawItem(LPDRAWITEMSTRUCT /*lpDrawItemStruct*/); protected: virtual void PreSubclassWindow(); private: CBrush m_normalBrush; CPen m_Pen; CBrush m_activeBrush; };
RoundButton.cpp
1 #include "StdAfx.h" 2 #include "RoundButton.h" 3 4 CRoundButton::CRoundButton(void) 5 {//初始化这三个变量 6 m_Pen.CreatePen(PS_SOLID,1,RGB(201,201,233)); 7 m_normalBrush.CreateSolidBrush(RGB(34,34,.34/*231,221,223*/));//正常状态下的按钮颜色 8 m_activeBrush.CreateSolidBrush(RGB(201,201,233));//按钮按下时的按钮颜色 9 } 10 11 CRoundButton::~CRoundButton(void) 12 {//删除三个变量 13 m_Pen.DeleteObject(); 14 m_normalBrush.DeleteObject(); 15 m_activeBrush.DeleteObject(); 16 } 17 18 void CRoundButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) 19 { 20 21 // TODO: 添加您的代码以绘制指定项 22 CDC * pDC=CDC::FromHandle(lpDrawItemStruct->hDC); //DC Device Context 设备上下文 获取当前窗口的设备环境 23 int nSaveDC=pDC->SaveDC();//存储当前设备环境,以便绘图结束时恢复原来状态 24 pDC->SelectObject(&m_normalBrush);//选择按钮正常状态(默认状态下)的画刷 25 pDC->SelectObject(&m_Pen);//选择画笔 26 CRect rct=lpDrawItemStruct->rcItem;//获取按钮矩形区域 27 if(lpDrawItemStruct->itemState&ODS_SELECTED)//绘制按钮按下时的颜色 28 { 29 pDC->SelectObject(&m_activeBrush); 30 } 31 32 pDC->Ellipse(&rct); 33 pDC->SetBkMode(TRANSPARENT);//重绘文本时不擦除背景,即透明模式,如果选择OPAQUE(不透明),在文本四周有白色矩形边框 34 CString strText; 35 GetWindowText(strText); 36 pDC->DrawText(strText,rct,DT_CENTER|DT_VCENTER|DT_SINGLELINE); 37 pDC->RestoreDC(nSaveDC); 38 39 } 40 41 void CRoundButton::PreSubclassWindow() 42 //PreSubclassWindow()该函数可以初始化子类窗口,做一些绘制子类窗口之前要做的事情,如按钮风格的修改,按钮形状的修改 43 { 44 // TODO: 在此添加专用代码和/或调用基类 45 46 ModifyStyle(0,BS_OWNERDRAW); //改为自绘风格 47 //绘制按钮可用区域,切掉四个边角 48 CRgn rgn; 49 CRect rct; 50 GetClientRect(&rct); 51 rgn.CreateEllipticRgnIndirect(&rct); //在按钮矩形内创建椭圆区域 52 ::SetWindowRgn(GetSafeHwnd(),(HRGN)rgn,true);//将椭圆区域应用到按钮上 53 CButton::PreSubclassWindow(); 54 }