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 9. Font<br />

CFont *ptrFont;<br />

if(!CDocument::OnNewDocument())return FALSE;<br />

ptrFont=dc.GetCurrentFont();<br />

ptrFont->GetLogFont(&lf);<br />

VERIFY(m_ftDraw.CreateFontIndirect(&lf));<br />

}<br />

return TRUE;<br />

This function will be called when the document is initialized. Within the function, variable m_ftDraw is<br />

used to create a default font. Since the document is always created before the view, creating the font in this<br />

function will guarantee that m_ftDraw will be a valid font when the view is created. This procedure can also<br />

be done in the constructor.<br />

To let the user select different types of fonts, a new command Dialog | Font is added to application’s<br />

mainframe menu IDR_MAINFRAME. The resource ID of this command is ID_DIALOG_FONT and the<br />

corresponding message handler is CGDIDoc::OnDialogFont(), which is implemented as follows:<br />

void CGDIDoc::OnDialogFont()<br />

{<br />

CFontDialog dlg;<br />

LOGFONT lf;<br />

}<br />

if(dlg.DoModal() == IDOK)<br />

{<br />

dlg.GetCurrentFont(&lf);<br />

m_ftDraw.DeleteObject();<br />

VERIFY(m_ftDraw.CreateFontIndirect(&lf));<br />

UpdateAllViews(NULL);<br />

}<br />

After a new font is selected by the user, we delete the old font and create a new one, then call function<br />

CDocument::UpdateAllViews(…) to update the client window.<br />

On the view side, we need to modify function CGDIView::OnDraw(…). In this function, the text string<br />

and the font are retrieved from the document, and are used to draw text in the client window:<br />

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

{<br />

CString szText;<br />

CFont *ptrFontOld;<br />

}<br />

CGDIDoc *pDoc=GetDocument();<br />

ASSERT_VALID(pDoc);<br />

szText=pDoc->GetText();<br />

ptrFontOld=pDC->SelectObject(pDoc->GetFont());<br />

pDC->TextOut(0, 0, szText);<br />

pDC->SelectObject(ptrFontOld);<br />

With the above implementation, the application will display a static string. Although we still can not<br />

input any character, the font for drawing the text can be changed through executing Dialog | Font<br />

command.<br />

9.5 One Line Text Editor, Step 2: Adding Caret<br />

Caret Functions<br />

Caret is a very important feature for text editor, it indicates the current editing position. This makes the<br />

interface more user friendly. Because there are many types of fonts in the system, and for each font, the<br />

251

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

Saved successfully!

Ooh no, something went wrong!