========================================================== ==================================
Title: Implementation of Button self-painting under MFC (3)
Abstract:
Note: MFC + VC2005
Date: 2010.7.20
Name: Zhu minglei
========================================================== ==================================
The button is drawn mainly in the DrawItem function. Below is a simple drawing.
First, draw the outer border of the button. Defines a member variable:
CPen m_OutBorderPen;
This is a paint brush used to draw the outer border of a button. It is created in the class constructor and destroyed in the class destructor. Then, in the DrawItem function, start to draw the outer border of the button:
CRect rect = lpDrawItemStruct-> rcItem;
CDC * pDC = CDC: FromHandle (lpDrawItemStruct-> hDC );
Int nSavedDC = pDC-> SaveDC ();
// Draw the outer border of the button
POINT pt;
Pt. x = 5;
Pt. y = 5;
CPen * pOldPen = pDC-> SelectObject (& m_OutBorderPen );
PDC-> RoundRect (& rect, pt );
PDC-> SelectObject (pOldPen );
After compilation, execute the program and check the effect:
The button outlines.
Step 2: Draw the background color of the button.
// Specifies the base color of the draw button.
Rect. DeflateRect (3, 3, 3, 3 );
CBrush * pOldBrush = pDC-> SelectObject (& m_BackgroundBrush );
PDC-> Rectangle (rect );
PDC-> SelectObject (pOldBrush );
Here is just a simple demonstration. The buttons are not necessarily nice. Set the base color of the button to pure white. The program execution result is as follows:
Step 3: Draw the text of the button.
// Draw button text
TCHAR strButtonText [MAX_PATH + 1];
: GetWindowText (m_hWnd, strButtonText, MAX_PATH); // obtain the button text
If (strButtonText! = NULL)
{
CFont * pFont = GetFont ();
CFont * pOldFont = pDC-> SelectObject (pFont );
CSize szExtent = pDC-> GetTextExtent (strButtonText, _ tcslen (strButtonText ));
CRect rectText = lpDrawItemStruct-> rcItem;
RectText. deflateRect (rect. centerPoint (). x-szExtent. cx/2, rect. centerPoint (). y-szExtent. cy/2, rect. centerPoint (). x-szExtent. cx/2, rect. centerPoint (). y-szExtent. cy/2 );
Int nOldBkMode = pDC-> SetBkMode (TRANSPARENT );
PDC-> DrawText (strButtonText,-1, rectText, DT_WORDBREAK | DT_CENTER );
PDC-> SelectObject (pOldFont );
PDC-> SetBkMode (nOldBkMode );
}
Re-compile. The execution result is as follows:
The basic appearance of the button has been drawn. Next, you need to draw the button when it is pressed, the cursor slides out, the cursor leaves, and so on. Of course, you also need to explore the circle button, triangle button, and irregular graph button painting. Tired. Write it here first.