程式語言 - MinGW - C/C++ - Set Scrollbar



參考資訊:
http://www.winprog.org/tutorial/
http://winapi.freetechsecrets.com/win32/
https://github.com/gammasoft71/Examples_Win32
http://masm32.com/board/index.php?topic=3584.0
https://learn.microsoft.com/en-us/windows/win32/winmsg/window-styles

當視窗的可視區域(如:300x300像素)小於顯示圖片大小(如:640x480像素)時,這時可以使用Windows視窗元件Scrollbar,用來做顯示位置調整的動作,Scrollbar元件有垂直和水平兩種方向並且提供視窗事件回報機制(WM_VSCROLL、WM_HSCROLL),因此,這裡的Scrollbar元件並不能夠自動幫忙做顯示位置調整的動作,取而代之的是,在收到WM_VSCROLL、WM_HSCROLL事件時,使用者必須自己決定哪些東西要顯示在視窗的可視區域上

main.c

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

HWND hWin = NULL;
WNDPROC defWndProc = NULL;

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg) {
    case WM_CLOSE:
        DestroyWindow(hWnd);
        return 0;
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    case WM_VSCROLL:
        switch (LOWORD(wParam)) {
        case SB_LINEUP:
            SetWindowText(hWnd, "LINE++");
            break;
        case SB_LINEDOWN:
            SetWindowText(hWnd, "LINE--");
            break;
        case SB_PAGEUP:
            SetWindowText(hWnd, "PAGE++");
            break;
        case SB_PAGEDOWN:
            SetWindowText(hWnd, "PAGE--");
            break;
        }
        break;
    }
    return CallWindowProc(defWndProc, hWnd, uMsg, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    hWin = CreateWindow(WC_DIALOG, "main", 
        WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_VSCROLL, 0, 0, 300, 300, NULL, NULL, NULL, NULL);
    defWndProc = (WNDPROC)SetWindowLongPtr(hWin, GWLP_WNDPROC, (long int)WndProc);

    SetScrollRange(hWin, SB_VERT, 0, 100, FALSE);
    SetScrollPos(hWin, SB_VERT, 50, TRUE);

    MSG msg = {0};
    while (GetMessage(&msg, NULL, 0, 0)) {
        DispatchMessage(&msg);
    }
    ExitProcess(0);
    return 0;
}

Line 18~33:處理Scrollbar訊息並且顯示在視窗標題
Line 41:WS_VSCROLL是垂直的Scrollbar,WS_HSCROLL則是水平的Scrollbar
Line 44:設定Scrollbar最大的範圍
Line 45:設定Scrollbar目前的位置

編譯、執行

$ i686-w64-mingw32-gcc -mwindows main.c -o main.exe
$ wine ./main.exe