MFC Scrollbar example
#include <afxwin.h>
#define ID_SCROLLBAR 1000
#define ID_STATIC 1001
class CSimpleApp : public CWinApp
{
public:
BOOL InitInstance();
};
class CMainFrame : public CFrameWnd
{
public:
CMainFrame();
afx_msg void SetLabel(int);
afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
DECLARE_MESSAGE_MAP()
CScrollBar wScrollbar;
CStatic wStatic;
};
BOOL CSimpleApp::InitInstance()
{
m_pMainWnd = new CMainFrame();
m_pMainWnd->ShowWindow(m_nCmdShow);
return TRUE;
}
CMainFrame::CMainFrame()
{
Create(NULL,
_T("MFC Scrollbar Example"),
WS_OVERLAPPEDWINDOW,
CRect(25, 25, 450, 170));
// Create static control
wStatic.Create(_T(""),
WS_CHILD | WS_VISIBLE | WS_BORDER,
CRect(25, 60, 75, 90),
this,
ID_STATIC);
// Create horizontal scrollbar
wScrollbar.Create(WS_CHILD | WS_VISIBLE | SBS_HORZ,
CRect(10, 10, 410, 50),
this,
ID_SCROLLBAR);
// Set scrollbar range and initial position
wScrollbar.SetScrollRange(0, 100, TRUE);
wScrollbar.SetScrollPos(0);
SetLabel(0);
}
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_HSCROLL()
END_MESSAGE_MAP()
CSimpleApp MFCApp1;
// Handles horizontal scrollbar messages
afx_msg void CMainFrame::OnHScroll(UINT nSBCode,
UINT nPos,
CScrollBar* pScrollBar)
{
int minpos;
int maxpos;
pScrollBar->GetScrollRange(&minpos, &maxpos);
int curpos = pScrollBar->GetScrollPos();
switch (nSBCode)
{
case SB_LEFT: // Scroll to minimum position
curpos = minpos;
break;
case SB_RIGHT: // Scroll to maximum position
curpos = maxpos;
break;
case SB_ENDSCROLL: // End of scrolling
break;
case SB_LINELEFT: // Scroll one line left
curpos--;
break;
case SB_LINERIGHT: // Scroll one line right
curpos++;
break;
case SB_PAGELEFT: // Scroll one page left
curpos -= 5;
break;
case SB_PAGERIGHT: // Scroll one page right
curpos += 5;
break;
case SB_THUMBPOSITION: // Thumb released
curpos = nPos;
break;
case SB_THUMBTRACK: // Thumb being dragged
curpos = nPos;
break;
}
// Keep position within the valid range
if (curpos < minpos)
curpos = minpos;
if (curpos > maxpos)
curpos = maxpos;
pScrollBar->SetScrollPos(curpos);
SetLabel(curpos);
CFrameWnd::OnHScroll(nSBCode, nPos, pScrollBar);
}
// Display scrollbar position in the static control
afx_msg void CMainFrame::SetLabel(int newvalue)
{
CString text;
text.Format(_T("%d"), newvalue);
wStatic.SetWindowText(text);
}