6.7 Add Scrolling Member Functions

This section explains the ninth step in writing Phone Book: add message-handler functions for vertical and horizontal scrolling.

·To add the scrolling message-handlers:

1.Add the following OnVScroll message-handler member function to the CMainWindow section of your VIEW.CPP file below the OnSize member function:

// CMainWindow::OnVScroll

// Translate scroll messages into Scroll increments and then

// checks the current position to determine if scrolling is possible

//

void CMainWindow::OnVScroll( UINT wParam, UINT pos, CWnd* )

{

short nScrollInc;

switch ( wParam )

{

case SB_TOP:

nScrollInc = -m_nVscrollPos;

break;

case SB_BOTTOM:

nScrollInc = m_nVscrollMax - m_nVscrollPos;

break;

case SB_LINEUP:

nScrollInc = -1;

break;

case SB_LINEDOWN:

nScrollInc = 1;

break;

case SB_PAGEUP:

nScrollInc = min( -1, -m_cyClient / m_cyChar );

break;

case SB_PAGEDOWN:

nScrollInc = max( 1, m_cyClient / m_cyChar );

break;

case SB_THUMBTRACK:

nScrollInc = pos - m_nVscrollPos;

break;

default:

nScrollInc = 0;

}

if ( nScrollInc = max( -m_nVscrollPos,

min( nScrollInc, m_nVscrollMax - m_nVscrollPos ) ) )

{

m_nVscrollPos += nScrollInc;

ScrollWindow( 0, -m_cyChar * nScrollInc );

SetScrollPos( SB_VERT, m_nVscrollPos );

UpdateWindow();

}

}

OnVScroll responds to mouse clicks in the vertical scrollbar. It uses a switch statement to determine what part of the scrollbar was clicked. It then translates the location information into scrolling offsets and scrolls the window to match.

2.Add the following OnHScroll message-handler member function to the CMainWindow section of your VIEW.CPP file below the OnVScroll member function:

// CMainWindow::OnHScroll

// Translate scroll messages into Scroll increments and then

// checks the current position to determine if scrolling is possible

//

void CMainWindow::OnHScroll( UINT wParam, UINT pos, CWnd* )

{

int nScrollInc;

switch ( wParam )

{

case SB_LINEUP:

nScrollInc = -1;

break;

case SB_LINEDOWN:

nScrollInc = 1;

break;

case SB_PAGEUP:

nScrollInc = -PAGESIZE;

break;

case SB_PAGEDOWN:

nScrollInc = PAGESIZE;

break;

case SB_THUMBPOSITION:

nScrollInc = pos - m_nHscrollPos;

break;

default:

nScrollInc = 0;

}

if ( nScrollInc = max( -m_nHscrollPos,

min( nScrollInc, m_nHscrollMax - m_nHscrollPos ) ) )

{

m_nHscrollPos += nScrollInc;

ScrollWindow( -m_cxChar * nScrollInc, 0 );

SetScrollPos( SB_HORZ, m_nHscrollPos );

UpdateWindow();

}

}

OnHScroll responds to the horizontal scrollbar.

To continue the tutorial, see “Add a Keyboard and Mouse Interface” on page 230. For more information about the scrolling message-handlers, see the following discussion.