WIN32滚动条

来源:互联网 发布:魏则西怎么样了 知乎 编辑:程序博客网 时间:2024/06/10 16:48

#include <windows.h>
#include <stdio.h>

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

static char szAppName[ ] = "APP9";
char buf[20];
const char * pszcText = "C++ Programming";
int i;
int iVPos;
int WINAPI WinMain(HINSTANCE hInstance,
       HINSTANCE hPrevInstance,
       LPSTR     lpCmdLine,
       int       nShowCmd)
{
 WNDCLASS wc;
 wc.cbClsExtra = 0;
 wc.cbWndExtra = 0;
 wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
 wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
 wc.hInstance = hInstance;
 wc.lpfnWndProc = WndProc;
 wc.lpszClassName = szAppName;
 wc.lpszMenuName = NULL;
 wc.style = CS_HREDRAW | CS_VREDRAW;
 if ( !RegisterClass( &wc ) )
 {
  MessageBox(NULL, "Can't register class!", "Can't register class!", NULL);
  return 1;
 }

 HWND hwnd = CreateWindow(szAppName,
        szAppName,
        WS_OVERLAPPEDWINDOW | WS_VSCROLL,
        0,
        0,
        400,
        400,
        NULL,
        NULL,
        hInstance,
        NULL);
 ShowWindow(hwnd, SW_SHOWNORMAL);
 UpdateWindow(hwnd);

 MSG msg;
 while ( GetMessage(&msg, NULL, 0, 0) )
 {
  TranslateMessage( &msg );
  DispatchMessage( &msg );
 }

 return msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
 static int cxChar, cyChar, cyClient;
 static HDC hdc;
 static PAINTSTRUCT ps;
 static TEXTMETRIC  tm;

 switch ( msg )
 {
 case WM_CREATE:
  hdc = GetDC(hwnd);
  GetTextMetrics(hdc, &tm);
  cxChar = tm.tmAveCharWidth;
  cyChar = tm.tmHeight + tm.tmExternalLeading;
  ReleaseDC(hwnd, hdc);
  SetScrollRange(hwnd, SB_VERT, 0, 40, FALSE);
  SetScrollPos(hwnd, SB_VERT, iVPos, FALSE);
  break;
 case WM_SIZE:
  cyClient = HIWORD(lParam);
  break;
 case WM_PAINT:
  hdc = BeginPaint(hwnd, &ps);
  for (i = 0; i < 40; ++i)
  {
   sprintf(buf, "%d : %s ", i + 1, pszcText);
   TextOut(hdc, 10, cyChar * (i - iVPos), buf, lstrlen(buf));
  }
  EndPaint(hwnd, &ps);
  break;
 case WM_VSCROLL:
  switch (LOWORD(wParam))
  {
  case SB_LINEDOWN:
   iVPos += 1;
   break;
  case SB_LINEUP:
   iVPos -= 1;
   break;
  case SB_PAGEDOWN:
   iVPos += cyClient / cyChar;
   break;
  case SB_PAGEUP:
   iVPos -= cyClient / cyChar;
   break;
  case SB_THUMBPOSITION:
   iVPos = HIWORD(wParam);
   break;
  }
  iVPos = max(0, min(iVPos, 39));
  if (iVPos != GetScrollPos(hwnd, SB_VERT))
  {
   SetScrollPos(hwnd, SB_VERT, iVPos, TRUE);
   InvalidateRect(hwnd, NULL, TRUE);
  }
  break;
 case WM_CLOSE:
  DestroyWindow(hwnd);
  break;
 case WM_DESTROY:
  PostQuitMessage( 0 );
  break;
 default:
  ;
  break;
 }

 return DefWindowProc(hwnd, msg, wParam, lParam);

原创粉丝点击