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 />

When we cut data to the clipboard, we also need to delete the selected text. So first a new function<br />

DeleteSelection() is declared in class CGDIDoc, it can be called to delete the currently selected text:<br />

……<br />

……<br />

……<br />

class CGDIDoc : public CDocument<br />

{<br />

public:<br />

}<br />

BOOL DeleteSelection();<br />

Function CGDIDoc::DeleteSelection() is implemented as follows:<br />

BOOL CGDIDoc::DeleteSelection()<br />

{<br />

CString szStr;<br />

int nSel;<br />

int nNum;<br />

if<br />

(<br />

m_nSelIndexEnd == -1 ||<br />

m_nSelIndexBgn == -1 ||<br />

m_nSelIndexEnd == m_nSelIndexBgn<br />

)return FALSE;<br />

if(m_nSelIndexEnd > m_nSelIndexBgn)<br />

{<br />

nSel=m_nSelIndexBgn;<br />

nNum=m_nSelIndexEnd-m_nSelIndexBgn;<br />

}<br />

else<br />

{<br />

nSel=m_nSelIndexEnd;<br />

nNum=m_nSelIndexBgn-m_nSelIndexEnd;<br />

}<br />

szStr=m_szText.Left(nSel);<br />

m_szText=m_szText.Mid(nSel+nNum);<br />

m_szText=szStr+m_szText;<br />

m_nCaretIndex=nSel;<br />

UpdateAllViews(NULL);<br />

GetCGDIView()->RedrawCaret();<br />

m_nSelIndexBgn=m_nSelIndexEnd=-1;<br />

}<br />

return TRUE;<br />

When there is no currently selected text, the function does nothing. Otherwise we proceed to delete the<br />

selected text.<br />

Because the ending selection index may be less than the beginning selection index, first we set the<br />

value of local variable nSel to the smaller selection index, and set the number of selected characters to<br />

another local variable nNum. Then the unselected text is combined together, and the caret index is adjusted.<br />

Next the caret and the client window are updated. Finally, both selection indices are set to -1, this indicates<br />

that currently there is no text being selected.<br />

We can call this function when DELETE key is pressed to delete the selected text, also we can call it<br />

when the selected text is being cut to the clipboard. In the sample, function CGDIDoc::DeleteChar() is<br />

modified as follows:<br />

void CGDIDoc::DeleteChar(BOOL bBefore)<br />

{<br />

CString szStr;<br />

if(DeleteSelection() == TRUE)return;<br />

if(bBefore == TRUE)<br />

270

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

Saved successfully!

Ooh no, something went wrong!