对话框的(上下/左右)滚动事件,比如,把一个比较大的对话框放入tab控件的某一页时,就需要添加滚动条。在使用了java和qt等图形界面化的集成开发环境之后,再使用MFC,就会发现,想要让一个对话框滚动是多么麻烦的一件事情。下面我记录一下自己在使用MFC对话框自己带的垂直滚动条的过程。
(1)设置对话框的vertical scrollbar属性为true;
(2)初始化滚动条,如下:
void Dlg_WholeTest_Test::initScrollbar()
{
SCROLLINFO scrollinfo;
GetScrollInfo(SB_VERT,&scrollinfo,SIF_ALL);
scrollinfo.nPage=10; //设置滑块大小
scrollinfo.nMax=75; //设置滚动条的最大位置0--75
SetScrollInfo(SB_VERT,&scrollinfo,SIF_ALL);
}
在OnInitDialog函数中调用该初始化函数即可。
(3)重新实现OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)消息处理函数。
void MyDialog::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) //对话框的滚动效果
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
SCROLLINFO scrollinfo;
GetScrollInfo(SB_VERT,&scrollinfo,SIF_ALL);
int unit=3;
switch (nSBCode)
{
case SB_LINEUP: //Scroll one line up
scrollinfo.nPos -= 1;
if (scrollinfo.nPos<scrollinfo.nMin)
{
scrollinfo.nPos = scrollinfo.nMin;
break;
}
SetScrollInfo(SB_VERT,&scrollinfo,SIF_ALL);
ScrollWindow(0,unit);
break;
case SB_LINEDOWN: //Scroll one line down
scrollinfo.nPos += 1;
if (scrollinfo.nPos+scrollinfo.nPage>scrollinfo.nMax) //此处一定要注意加上滑块的长度,再作判断
{
scrollinfo.nPos = scrollinfo.nMax;
break;
}
SetScrollInfo(SB_VERT,&scrollinfo,SIF_ALL);
ScrollWindow(0,-unit);
break;
case SB_PAGEUP: //Scroll one page up.
scrollinfo.nPos -= 5;
if (scrollinfo.nPos<=scrollinfo.nMin)
{
scrollinfo.nPos = scrollinfo.nMin;
break;
}
SetScrollInfo(SB_VERT,&scrollinfo,SIF_ALL);
ScrollWindow(0,unit*5);
break;
case SB_PAGEDOWN: //Scroll one page down
scrollinfo.nPos += 5;
if (scrollinfo.nPos+scrollinfo.nPage>=scrollinfo.nMax) //此处一定要注意加上滑块的长度,再作判断
{
scrollinfo.nPos = scrollinfo.nMax;
break;
}
SetScrollInfo(SB_VERT,&scrollinfo,SIF_ALL);
ScrollWindow(0,-unit*5);
break;
case SB_ENDSCROLL: //End scroll
break;
case SB_THUMBPOSITION: //Scroll to the absolute position. The current position is provided in nPos
break;
case SB_THUMBTRACK: //Drag scroll box to specified position. The current position is provided in nPos
ScrollWindow(0,(scrollinfo.nPos-nPos)*unit);
scrollinfo.nPos = nPos;
SetScrollInfo(SB_VERT,&scrollinfo,SIF_ALL);
break;
}
CDialog::OnVScroll(nSBCode, nPos, pScrollBar);
}