11.04.2014 Views

Advanced MFC Programming

Advanced MFC Programming

Advanced MFC Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 9. Font<br />

the same, it indicates that there is no text being selected. The two variables are initialized in the constructor<br />

as follows:<br />

……<br />

CGDIDoc::CGDIDoc()<br />

{<br />

}<br />

m_nCaretIndex=0;<br />

m_nSelIndexBgn=-1;<br />

m_nSelIndexEnd=-1;<br />

In CGDIView::OnDraw(…), we need to retrieve the values of m_nSelIndexBgn and m_nSelIndexEnd,<br />

swap forground and background colors for the selected text when outputting text string to the client<br />

window. The following is the modified function CGDIView::OnDraw(…):<br />

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

{<br />

CString szText;<br />

CString szStr;<br />

CFont *ptrFontOld;<br />

int nSelIndexBgn;<br />

int nSelIndexEnd;<br />

int nSel;<br />

UINT uTextAlign;<br />

COLORREF colorFg;<br />

COLORREF colorBk;<br />

}<br />

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

ASSERT_VALID(pDoc);<br />

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

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

nSelIndexBgn=pDoc->GetSelIndexBgn();<br />

nSelIndexEnd=pDoc->GetSelIndexEnd();<br />

if<br />

(<br />

nSelIndexBgn == -1 ||<br />

nSelIndexEnd == -1 ||<br />

(nSelIndexBgn == nSelIndexEnd)<br />

)<br />

{<br />

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

}<br />

else<br />

{<br />

if(nSelIndexEnd < nSelIndexBgn)<br />

{<br />

nSel=nSelIndexBgn;<br />

nSelIndexBgn=nSelIndexEnd;<br />

nSelIndexEnd=nSel;<br />

}<br />

uTextAlign=pDC->SetTextAlign(TA_UPDATECP);<br />

szStr=szText.Left(nSelIndexBgn);<br />

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

colorFg=pDC->GetTextColor();<br />

colorBk=pDC->GetBkColor();<br />

pDC->SetTextColor(colorBk);<br />

pDC->SetBkColor(colorFg);<br />

szStr=szText.Mid(nSelIndexBgn, nSelIndexEnd-nSelIndexBgn);<br />

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

pDC->SetTextColor(colorFg);<br />

pDC->SetBkColor(colorBk);<br />

szStr=szText.Mid(nSelIndexEnd);<br />

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

pDC->SetTextAlign(uTextAlign);<br />

}<br />

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

265

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

Saved successfully!

Ooh no, something went wrong!