Now that you have enabled the Circle control's background color property and set its default background color, the final step is to modify the CCircCtrl::OnDraw
function in CIRCCTL.CPP to implement the painting behavior.
As created by ControlWizard, the CCircCtrl::OnDraw
function implements the basic Circle control drawing behavior:
void CCircCtrl::OnDraw(
CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid)
{
// TODO: Replace the following code with your own drawing code.
pdc->FillRect(rcBounds, CBrush::FromHandle((HBRUSH)GetStockObject(WHITE_BRUSH)));
pdc->Ellipse(rcBounds);
}
The default behavior of the OnDraw
function is to draw an ellipse with a white background — exactly what was displayed in Test Container earlier.
To modify OnDraw
to use the background color value defined by the Circle control's BackColor property, remove the //TODO comment line and the line on which FillRect
is called, and modify the code as follows (beginning with the fourth line in the code example, this is new code that you will be adding):
void CCircCtrl::OnDraw(
CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid)
{
CBrush* pOldBrush;
CBrush bkBrush(TranslateColor(GetBackColor()));
CPen* pOldPen;
// Paint the background using the BackColor property
pdc->FillRect(rcBounds, &bkBrush);
// Draw the ellipse using the BackColor property and a black pen
pOldBrush = pdc->SelectObject(&bkBrush);
pOldPen = (CPen*)pdc->SelectStockObject(BLACK_PEN);
pdc->Ellipse(rcBounds);
pdc->SelectObject(pOldPen);
pdc->SelectObject(pOldBrush);
}
The code constructs a brush, called bkBrush
, that uses the BackColor property color. Because a COLORREF value is expected for initializing the brush, and the BackColor property value is an OLE_COLOR value, TranslateColor is called first. The bounding rectangle of the control is painted using CDC::FillRect, specifying bkBrush
as the fill brush.
The ellipse is drawn within the bounding rectangle of the control using the CDC::Ellipse member function. Before the ellipse is drawn, the background color brush and the pen must be selected into the device context. This is done by calling CDC::SelectObject, as shown in the code. Now when the ellipse is drawn, it is filled with the proper background color and drawn using a black pen. Finally, the old brush and pen are selected back into the device context, restoring the device context to the state in which it entered the OnDraw
function.