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 8. DC, Pen, Brush and Palette<br />

We can declare a brush type variable using class CBrush, and create various kind of brushes by calling<br />

any of the following functions: CBrush::CreateSolidBrush(…), CBrush::CreateHatchBrush(…),<br />

CBrush::CreatePatternBrush(…). In the sample, only solid brush is used. In Windows, there are several<br />

pre-implemented default GDI objects that can be retrieved and used at any time. These objects include<br />

pens, brushes, fonts, etc. We can get any object by calling ::GetStockObject(…) API function. The<br />

returned value is a handle that could be attached to a GDI variable (declared by <strong>MFC</strong> class) of the same<br />

type. For example, the following code shows how to obtain a gray brush and attach it to a CBrush type<br />

variable:<br />

CBrush brush;<br />

brush.Attach(::GetStockObject(GRAY_BRUSH));<br />

//After some drawing<br />

brush.Detach();<br />

We need to detach the object before the GDI variable goes out of scope.<br />

When a rectangle is not finally fixed, we may want to draw only its border and leave its interior<br />

unpainted. To implement this, we can select a NULL (hollow) brush into the device context. A hollow<br />

brush can be obtained by calling function ::GetStockObject(…) using HOLLOW_BTRUSH or NULL_BRUSH flag.<br />

Sample 8.2-1\GDI demonstrates how to implement an interactive environment to let the user draw<br />

rectangles. It is an SDI application generated by Application Wizard. Like what we implemented in sample<br />

8.1\GDI, first some member variables and functions are declared in the document for storing rectangles:<br />

……<br />

……<br />

……<br />

class CGDIDoc : public CDocument<br />

{<br />

public:<br />

void AddRect(CRect rect){m_paRects.Add(new CRect(rect));}<br />

CRect *GetRect(int nID){return (CRect *)m_paRects.GetAt(nID);}<br />

int GetNumOfRects(){return m_paRects.GetSize();}<br />

protected:<br />

CPtrArray m_paRects;<br />

};<br />

In the destructor, all the objects in array m_paRects are deleted:<br />

CGDIDoc::~CGDIDoc()<br />

{<br />

while(m_paRects.GetSize())<br />

{<br />

delete m_paRects.GetAt(0);<br />

m_paRects.RemoveAt(0);<br />

}<br />

}<br />

In class CGDIView, some new variables are declared, they will be used to record rectangles, erasing<br />

state and window capture state:<br />

……<br />

……<br />

class CGDIView : public CView<br />

{<br />

protected:<br />

CRect m_rectDraw;<br />

BOOL m_bNeedErase;<br />

BOOL m_bCapture;<br />

};<br />

Two Boolean type variables are initialized in the constructor:<br />

208

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

Saved successfully!

Ooh no, something went wrong!