以下是一个 Windows 滚动条的示例代码:
```c++
#include <windows.h>
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
// 注册窗口类
WNDCLASS wc = {0};
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszClassName = TEXT("ScrollDemo");
RegisterClass(&wc);
// 创建窗口
HWND hwnd = CreateWindow(TEXT("ScrollDemo"), TEXT("Scroll Demo"), WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 400, 300, NULL, NULL, hInstance, NULL);
// 显示窗口
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// 消息循环
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
static int yPos;
static SCROLLINFO si = {0};
si.cbSize = sizeof(si);
si.fMask = SIF_RANGE | SIF_POS | SIF_PAGE | SIF_TRACKPOS;
si.nMin = 0;
si.nMax = 1000;
si.nPos = 0;
si.nPage = 100;
switch (msg) {
case WM_CREATE:
SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
break;
case WM_VSCROLL:
switch (LOWORD(wParam)) {
case SB_LINEUP:
yPos = si.nPos - 10;
break;
case SB_LINEDOWN:
yPos = si.nPos + 10;
break;
case SB_PAGEUP:
yPos = si.nPos - si.nPage;
break;
case SB_PAGEDOWN:
yPos = si.nPos + si.nPage;
break;
case SB_THUMBTRACK:
yPos = HIWORD(wParam);
break;
default:
break;
}
yPos = max(0, yPos);
yPos = min(si.nMax - (int)si.nPage + 1, yPos);
if (yPos != si.nPos) {
si.nPos = yPos;
SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
ScrollWindow(hwnd, 0, -(si.nPos - yPos), NULL, NULL);
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
RECT rc;
GetClientRect(hwnd, &rc);
for (int i = 0; i < 100; i++) {
TCHAR buf[16];
wsprintf(buf, TEXT("%d"), i);
TextOut(hdc, rc.left + 10, rc.top + i * 20 - si.nPos, buf, lstrlen(buf));
}
EndPaint(hwnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}