Handling The ScrollBar

Here is a simple example illustrating how to programmatically handle the scroll bar (and it's messages).

1. First set up the dimensions of the control:

  SCROLLINFO ScrollInfo;
  ScrollInfo.cbSize = sizeof(ScrollInfo);     // size of this structure
  ScrollInfo.fMask = SIF_ALL;                 // parameters to set
  ScrollInfo.nMin = 0;                        // minimum scrolling position
  ScrollInfo.nMax = 100;                      // maximum scrolling position
  ScrollInfo.nPage = 40;                      // the page size of the scroll box
  ScrollInfo.nPos = 50;                       // initial position of the scroll box
  ScrollInfo.nTrackPos = 0;                   // immediate position of a scroll box that the user is dragging
2. Now override the WM_VSCROLL or WM_HSCROLL (for a horizontal control) function in Your ScrollBar class:

void CMyScrollBar::VScroll(UINT nSBCode, UINT nPos) 
  SCROLLINFO ScrollInfo;
  GetScrollInfo(&ScrollInfo);  // get information about the scroll

    case SB_BOTTOM:         //Scrolls to the lower right. 

    case SB_ENDSCROLL:      //Ends scroll. 

    case SB_LINEDOWN:       //Scrolls one line down. 
      SetScrollPos(GetScrollPos() + 1);

    case SB_LINEUP:         //Scrolls one line up. 
      SetScrollPos(GetScrollPos() - 1);

    case SB_PAGEDOWN:       //Scrolls one page down. 
      SetScrollPos(GetScrollPos() + ScrollInfo.nPage);

    case SB_PAGEUP:         //Scrolls one page up. 
      SetScrollPos(GetScrollPos() - ScrollInfo.nPage);

    case SB_THUMBPOSITION:  //The user has dragged the scroll box (thumb) and released the mouse button. The nPos parameter indicates the position of the scroll box at the end of the drag operation. 

    case SB_THUMBTRACK:     //The user is dragging the scroll box. This message is sent repeatedly until the user releases the mouse button. The nPos parameter indicates the position that the scroll box has been dragged to. 

    case SB_TOP:            //Scrolls to the upper left. 
3.That's it! With this code snippet, you can easily add a scrollbar control to your application and insert your own application specific logic to handle the different messages sent to your application when the user scrolls your document.

This article was originally published on July 28th, 1999

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date