Wednesday, May 19, 2010

Adding custom draw functionality to an MFC CButton

We will start by defining a subclass CBDButton to the MFC class CButton.


  1: class CBDButton : public CButton
  2: {
  3: public:
  4:     // overwrite void DrawItem function and draw your button
  5:     void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
  6: };
  7: 


As you can notice above, we have overridden one function DrawItem in this class. Lets now look at its implementation.



 



  1: void CBDButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
  2: {
  3:     // TODO: Add your code to draw the specified item
  4:     UINT uStyle = DFCS_BUTTONPUSH;
  5: 
  6:     // This code only works with buttons.
  7:     ASSERT(lpDrawItemStruct->CtlType == ODT_BUTTON);
  8: 
  9:     // If drawing selected, add the pushed style to DrawFrameControl.
 10:     if (lpDrawItemStruct->itemState & ODS_SELECTED)
 11:     {
 12:         uStyle |= DFCS_PUSHED;
 13:     }
 14: 
 15:     CDC dc;
 16:     dc.Attach(lpDrawItemStruct->hDC);
 17: 
 18:     // Draw the button frame.
 19:     dc.DrawFrameControl(&lpDrawItemStruct->rcItem, DFC_BUTTON, uStyle);
 20: 
 21:     CRect rect = lpDrawItemStruct->rcItem;
 22:     rect.left = rect.left + 1;
 23:     rect.right = rect.right - 2;
 24:     rect.top = rect.left + 1;
 25:     rect.bottom = rect.bottom - 2;
 26:     dc.FillSolidRect(rect, m_clrBk);
 27: 
 28:     // Get the button's text.
 29:     CString strText;
 30:     GetWindowText(strText);
 31:     // Draw the button text using the text color.
 32:     COLORREF crOldColor = dc.SetTextColor(m_crText);
 33:     dc.DrawText(strText, strText.GetLength(), &lpDrawItemStruct->rcItem, DT_SINGLELINE|DT_VCENTER|DT_CENTER);
 34:     dc.SetTextColor(crOldColor);
 35: 
 36:     dc.Detach();
 37: }

No comments: