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

CString szSub;<br />

int nFwd;<br />

}<br />

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

nFwd=szSub.Find(' ');<br />

if(nFwd == -1)EndCaret();<br />

else<br />

{<br />

m_nCaretIndex+=nFwd+1;<br />

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

}<br />

void CGDIDoc::BackwardCaretToBlank()<br />

{<br />

CString szSub;<br />

int nBkd;<br />

}<br />

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

nBkd=szSub.ReverseFind(' ');<br />

if(nBkd == -1)HomeCaret();<br />

else<br />

{<br />

m_nCaretIndex-=szSub.GetLength()-nBkd;<br />

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

}<br />

Within the two functions, a local variable szSub is used to store the sub-string before or after the caret,<br />

and function CString::Find(…) or CString::ReverseFind(…) is called to find the position of the nearest<br />

blank. In case the blank is not found, we need to move the caret to the beginning or end of the text. If it is<br />

found, we just increment or decrement m_nCaretIndex by an appropriate value.<br />

On the view side, we need to move the caret when any of the following keys is pressed together with<br />

CTRL: HOME, END, Left and Right ARROW. These keystroke events can be trapped by handling<br />

WM_KEYDOWN message. To detect if the CTRL key is held down, we can call API function<br />

::GetKeyState(…) to check the key state.<br />

Function ::GetKeyState(…) can be used to check the current state of any key. We need to pass the<br />

virtual key code (such as VK_CONTROL, VK_SHIFT…) to this function when making the call. The returned<br />

value is a SHORT type integer. The high order of this value indicates if the key is held down, the lower order<br />

indicates if the key is toggled, which is applicable to keys such as CAPS LOCK, NUM LOCK or INSERT.<br />

Moving Caret Using Keyboard<br />

Function CGDIView::OnKeyDown(…) is modified as follows to add the new features to the application:<br />

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

{<br />

CGDIDoc *ptrDoc;<br />

SHORT nKeyState;<br />

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

ASSERT(ptrDoc);<br />

switch(nChar)<br />

{<br />

case VK_LEFT:<br />

{<br />

nKeyState=GetKeyState(VK_CONTROL);<br />

if(HIBYTE(nKeyState) != 0)<br />

{<br />

ptrDoc->BackwardCaretToBlank();<br />

}<br />

else ptrDoc->BackwardCaret();<br />

break;<br />

}<br />

case VK_RIGHT:<br />

{<br />

260

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

Saved successfully!

Ooh no, something went wrong!