自定义按钮类

来源:互联网 发布:stm8s003k3t6数据手册 编辑:程序博客网 时间:2024/06/05 09:18

 

1.      新建一个MFC类,名称为CCustomButton,父类CButton

2.      构造函数中初始化按钮字体

     CCustomButton::CCustomButton()

{

      Font.CreateFont( 12, 0, 0, 0, FW_HEAVY, 0, 0, 0, ANSI_CHARSET, \

             OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, \

             VARIABLE_PITCH | FF_SWISS, "MS Sans Serif" );

}

3.      改写按钮类的DrawItem虚方法

void CCustomButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)

{

      // TODO: Add your code to draw the specified item

             if (lpDrawItemStruct->CtlType==ODT_BUTTON )

      {

             CDC *pBtnDC = CDC::FromHandle(lpDrawItemStruct->hDC);      //获取按钮关联的DC

      //获取按钮的绘画区域

      CRect BtnRC = lpDrawItemStruct->rcItem;

      //获取按钮的当前状态

      int BtnState = lpDrawItemStruct->itemState;

      

      //获取按钮文本

      CString BtnText;

      GetWindowText(BtnText);

 

      CBrush           Brush;

      CBrush           *pOldBrush;

      CPoint           PT(2,2);

      

      pBtnDC->SelectObject(&Font);

      pBtnDC->SetTextColor( RGB( 255, 255, 250 ) );

      //如果按钮获得焦点或按钮被选中

      if (BtnState & ODS_SELECTED || BtnState & ODS_FOCUS)

      {

             Brush.CreateSolidBrush( RGB( 160, 160, 160 ) );

             pBtnDC->SetTextColor( RGB( 50, 50, 250 ) );

      }

      else

      {

             CBitmap bmp;

             bmp.LoadBitmap(IDB_BITMAP1);

             Brush.CreatePatternBrush(&bmp);

      }

      pOldBrush = pBtnDC->SelectObject( &Brush );

      pBtnDC->RoundRect(&BtnRC, PT);

 

      pBtnDC->SetBkMode(TRANSPARENT);

      pBtnDC->DrawText(BtnText, &BtnRC, DT_CENTER | DT_VCENTER | DT_SINGLELINE);

      pBtnDC->DeleteDC();  

      Brush.DeleteObject();

      }    

}

4.      设置按钮的Owner Draw属性为True.这时按钮没有回车响应,需要截获回车键按下和抬起的消息响应

BOOL CCustomButton::PreTranslateMessage(MSG* pMsg)

{

      if(pMsg->hwnd==this->GetSafeHwnd()&&pMsg->message==WM_KEYDOWN && pMsg->wParam==13)

      {

             pMsg->lParam=0;

             pMsg->message=WM_LBUTTONDOWN;

      }

      if(pMsg->hwnd==this->GetSafeHwnd()&&pMsg->message==WM_KEYUP && pMsg->wParam==13)

      {

             pMsg->lParam=0;

             pMsg->message=WM_LBUTTONUP;

      }

      return CButton::PreTranslateMessage(pMsg);

}

5.      在需要重绘按钮的对话框中引用自定义类,然后CCustomButton m_BTLogin;

6.          CDialog::DoDataExchange(pDX);

      //{{AFX_DATA_MAP(CLogin)后加入DDX_Control(pDX, IDC_LOGIN, m_BTLogin);