11.04.2014 Views

Advanced MFC Programming

Advanced MFC Programming

Advanced MFC Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 11. Sample: Simple Paint<br />

Using Region<br />

Like any other GDI object, before using the region, we must first select it into the DC. The difference<br />

between using region and other GDI objects is that we need to call function CDC::SelectClipRgn(…) to<br />

select the region instead of calling function CDC::SelectObject(…).<br />

Function CDC::SelectClipRgn(…) has two versions:<br />

virtual int CRgn::SelectClipRgn(CRgn* pRgn);<br />

int CRgn::SelectClipRgn(CRgn* pRgn, int nMode);<br />

For the second version of this function, parameter nMode specifies how to combine the new region with<br />

the region being currently selected by the DC. Again, it can be set to any of the following flags: RGN_AND,<br />

RGN_COPY, RGN_DIFF, RGN_OR and RGN_XOR.<br />

After using the region, we must select it out of the DC before deleting it. To select a region out of the<br />

DC, we can call function CDC::SelectClipRgn(…) and pass a NULL pointer to it. For example, the<br />

following statement selects the region out of DC (pointed by pDC):<br />

pDC->SelectClipRgn(NULL);<br />

A region can be deleted by calling function CGDIObject::DeleteObject(). Also, the destructor of<br />

CRgn will call this function automatically, so usually there is no need to delete the region unless we want to<br />

reinitialize it.<br />

Sample<br />

Sample 11.6\GDI is a standard SDI application generated by Application Wizard. In the sample, two<br />

variables are declared in class CGDIView: CGDIView::m_rgnRect and CGDIView::m_rgnEllipse. They will<br />

be used to create two regions, one is rectangular and one is elliptical. The two regions will be combined<br />

together to create a new region that is the difference of the two. We will select this region into the client<br />

window’s DC, and output text to the whole window. As we will see, only the area that is within the region<br />

will have the text output.<br />

The regions are created in the constructor of class CGDIView:<br />

CGDIView::CGDIView()<br />

{<br />

m_rgnRect.CreateRectRgn(0, 0, 400, 400);<br />

m_rgnEllipse.CreateEllipticRgn(50, 50, 350, 350);<br />

m_rgnRect.CombineRgn(&m_rgnRect, &m_rgnEllipse, RGN_DIFF);<br />

}<br />

The final region will look like the shaded area shown in Figure 11-6.<br />

Figure 11-6. Combine a rectangular region and an elliptical region together<br />

In function CGDIView::OnDraw(…), string “Clip Region” is output repeatedly until all the client<br />

window is covered by this text:<br />

void CGDIView::OnDraw(CDC* pDC)<br />

{<br />

352

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!