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

}<br />

szStr=szStr.Right(szStr.GetLength()-m_nCaretIndex);<br />

m_szText+=szStr;<br />

UpdateAllViews(NULL);<br />

BackwardCaret();<br />

}<br />

}<br />

else<br />

{<br />

if(m_nCaretIndex != m_szText.GetLength())<br />

{<br />

szStr=m_szText;<br />

m_szText=m_szText.Left(m_nCaretIndex);<br />

szStr=szStr.Right(szStr.GetLength()-m_nCaretIndex-1);<br />

m_szText+=szStr;<br />

UpdateAllViews(NULL);<br />

}<br />

}<br />

To delete the character before the current caret, we divide the text into two sub-strings, delete the last<br />

character of the first sub-string, and re-combine them. Then we update the view, and move caret one<br />

character left. When deleting the character after the caret, we do not need to change the position of the<br />

caret.<br />

Message WM_CHAR<br />

Now we need to use the above two member functions. In the sample, message WM_CHAR is handled to<br />

implement keyboard input. The difference between WM_CHAR and WM_KEYDOWN messages is that WM_CHAR is<br />

sent only for printable characters along with the following five keys: ESCAPE, TAB, BACK SPACE and<br />

ENTER. Message WM_KEYDOWN will be sent for all types of key strokes.<br />

In the sample, the message handler of WM_CHAR is CGDIView::OnChar(…), it is implemented as follows<br />

in the sample:<br />

void CGDIView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)<br />

{<br />

CGDIDoc *ptrDoc;<br />

}<br />

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

if(nChar != VK_RETURN && nChar != VK_ESCAPE && nChar != VK_TAB)<br />

{<br />

if(nChar == VK_BACK)ptrDoc->DeleteChar(TRUE);<br />

else ptrDoc->AddChar(nChar, nRepCnt);<br />

}<br />

CScrollView::OnChar(nChar, nRepCnt, nFlags);<br />

We neglect the ENTER, TAB and ESCAPE key strokes. For BACK SPACE key stroke, we delete the<br />

character before the current caret. For all other cases, we insert character at the current caret position.<br />

The DELETE key stroke can not be detected by this message handler, we need to trap and handle it in<br />

function CGDIView::OnKeyDown(…):<br />

……<br />

void CGDIView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)<br />

{<br />

}<br />

case VK_RIGHT:<br />

{<br />

ptrDoc->ForwardCaret();<br />

break;<br />

}<br />

case VK_DELETE:<br />

{<br />

ptrDoc->DeleteChar(FALSE);<br />

break;<br />

}<br />

258

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

Saved successfully!

Ooh no, something went wrong!