第一步,在 CreateWindow 中添加 WS_VSCROLL 如下:
hwnd = CreateWindow(szClsName, TEXT("Scroll Test."), WS_OVERLAPPEDWINDOW | WS_VSCROLL, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);
第二步,添加 WM_VSCROLL 响应:
case WM_VSCROLL:
switch(LOWORD){wParam}
{
case SB_THUMBTRACK:
nVPos = HIWORD(wParam);
break;
case SB_PAGEDOWN:
nVPos += nyClient / nyChar;
break;
case SB_PAGEUP:
nVPos -= nyClinet / nyChar;
break;
case SB_LINEDOWN:
nVPos += 1;
break;
case SB_LINEUP:
nVPos -= 1;
break;
}
nVPos = max(0, min(nVPos, NUMLINES - nyClinet / nyChar));
if(nVPos != GetScrollPos(hwnd, SB_VERT)) //滑块位置改变
{
SetScrollPos(hwnd, SB_VERT, nVPos, TRUE); //重设位置
InvalidateRect(hwnd, NULL, TRUE); //重绘显示区
}
第三步:添加绘制响应
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
for(i = 0; i < NUMLINES; i++)
{
y = nyChar * (i - nVPos);
TextOut(hdc, 0, y, sysmetrics[i].szLabel, lstrlen(sysmetrics[i].szLabel));
TextOut(hdc, 22*nxCaps, y,
sysmetrics[i].szDesc, lstrlen(sysmetrics[i].szDesc));
SetTextAlign(hdc, TA_RIGHT | TA_TOP);
TextOut(hdc, 22*nxCaps + 40*nxChar, y,
szBuf, wsprintf(szBuf, TEXT("%d"), GetSystemMetrics(sysmetrics[i].Index)));
SetTextAlign(hdc, TA_LEFT | TA_TOP);
}
EndPaint(hwnd, &ps);
第四步,当窗口大小发生改变时重绘
case WM_SIZE:
nyClient = HIWORD(lParam);
SetScrollRange(hwnd, SB_VERT, 0, NUMLINES - nyClient / nyChar, FALSE);
SetScrollPos(hwnd, SB_VERT, nVPos, TRUE);
if((NUMLINES - nVPos)*nyChar < nyClient && NUMLINES * nyChar > nyClient)
{
nVPos = NUMLINES - nyClient / nyChar;
//PostMessage(hwnd, WM_VSCROLL, (nVPos << 16) & SB_THUMBTRACK, 0);
}
在vc++中为窗口增加滚动条的方法:
Add a message handler for the WM_VSCROLL message to the OnVScroll method:
void CTestDlg::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
// TODO: Add your message handler code here and/or call default.
int nDelta;
int nMaxPos = m_rect.Height() - m_nCurHeight;
switch (nSBCode)
{
case SB_LINEDOWN:
if (m_nScrollPos >= nMaxPos)
return;
nDelta = min(nMaxPos/100,nMaxPos-m_nScrollPos);
break;
case SB_LINEUP:
if (m_nScrollPos <= 0)
return;
nDelta = -min(nMaxPos/100,m_nScrollPos);
break;
case SB_PAGEDOWN:
if (m_nScrollPos >= nMaxPos)
return;
nDelta = min(nMaxPos/10,nMaxPos-m_nScrollPos);
break;
case SB_THUMBPOSITION:
nDelta = (int)nPos - m_nScrollPos;
break;
case SB_PAGEUP:
if (m_nScrollPos <= 0)
return;
nDelta = -min(nMaxPos/10,m_nScrollPos);
break;
default:
return;
}
m_nScrollPos += nDelta;
SetScrollPos(SB_VERT,m_nScrollPos,TRUE);
ScrollWindow(0,-nDelta);
CDialog::OnVScroll(nSBCode, nPos, pScrollBar);
}
显示数据 用控件 CListCtrl吧,
自己给窗口 加滚动条,在显示 滚动 很麻烦