Adding Keyboard Scrolling

The biggest problem with the scroll view is probably the easiest to fix: the lack of keyboard support. You simply need to supply an OnKeyDown handler. When the view detects a keystroke, it calls KeyScroll, a function you can easily cut and paste into your own view. This function examines the virtual key code and simulates a scroll event based on the key.

You can easily modify this function to handle other keystrokes. You could also respect shift states. For example, you might make CTRL+HOME do something different from just HOME by itself. Another possibility is that you want scrolling to occur only if the SHIFT key is down. You can do all of that by using the GetKeyState call to determine if the particular modifier key is up or down.

 

void CKeyScrlView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
        for (unsigned int i=0;i<nRepCnt&&processed;i++)
                KeyScroll(nChar);
        CScrollView::OnKeyDown(nChar, nRepCnt, nFlags);
}

// Convert keystrokes to quasi-mouse messages
void CKeyScrlView::KeyScroll(UINT nChar)
{
        switch (nChar)
                {
                case VK_UP:
                        OnVScroll(SB_LINEUP,0,NULL);
                        break;
                case VK_DOWN:
                        OnVScroll(SB_LINEDOWN,0,NULL);
                        break;
                case VK_LEFT:
                        OnHScroll(SB_LINELEFT,0,NULL);
                        break;
                case VK_RIGHT:
                        OnHScroll(SB_LINERIGHT,0,NULL);
                        break;
                case VK_HOME:
                        OnHScroll(SB_LEFT,0,NULL);
                        break;
                case VK_END:
                        OnHScroll(SB_RIGHT,0,NULL);
                        break;
                case VK_PRIOR:
                        OnVScroll(SB_PAGEUP,0,NULL);
                        break;
                case VK_NEXT:
                        OnVScroll(SB_PAGEDOWN,0,NULL);
                        break;
                }
}