控件–ToolBar-WindowsAPI论坛-WindowsAPI-津桥芝士平台

控件–ToolBar

使用WindowsAPI,创建ToolBar控件:

#include <windows.h>
#include <commctrl.h>

#pragma comment(lib, "comctl32.lib")

#define ID_TOOLBAR 201

LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
    switch (message) {
    case WM_CREATE: {
        // 创建工具条控件
        HWND hwndToolBar = CreateToolbarEx(hwnd, WS_CHILD | WS_VISIBLE | TBSTYLE_TOOLTIPS,
            ID_TOOLBAR, 0, NULL, 0, NULL, 0,
            0, 0, 0, 0, sizeof(TBBUTTON));

        // 添加按钮到工具条
        TBBUTTON tbb[3];
        for (int i = 0; i < 3; ++i) {
            tbb[i].iBitmap = -1; // 不使用图标
            tbb[i].idCommand = 1000 + i; // 按钮 ID
            tbb[i].fsState = TBSTATE_ENABLED;
            tbb[i].fsStyle = TBSTYLE_BUTTON;
            tbb[i].dwData = 0;
            tbb[i].iString = (INT_PTR)L"Button"; // 按钮文本
        }

        SendMessage(hwndToolBar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
        SendMessage(hwndToolBar, TB_ADDBUTTONS, 3, (LPARAM)&tbb);
        SendMessage(hwndToolBar, TB_AUTOSIZE, 0, 0);

        break;
    }
    case WM_SIZE: {
        // 调整工具条控件的大小
        RECT rc;
        GetClientRect(hwnd, &rc);
        MoveWindow(GetDlgItem(hwnd, ID_TOOLBAR), 0, 0, rc.right, 30, TRUE); // 30 是工具条的高度
        break;
    }
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hwnd, message, wParam, lParam);
    }
    return 0;
}

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow) {
    // 初始化 Common Controls
    INITCOMMONCONTROLSEX icex;
    icex.dwSize = sizeof(icex);
    icex.dwICC = ICC_BAR_CLASSES; // 初始化工具条类
    InitCommonControlsEx(&icex);

    // 创建窗口类
    WNDCLASS wc = {};
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = L"ToolBarExample";
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);

    RegisterClass(&wc);

    // 创建窗口
    HWND hwnd = CreateWindowEx(
        0, L"ToolBarExample", L"ToolBar Control Example",
        WS_OVERLAPPEDWINDOW | WS_VISIBLE,
        CW_USEDEFAULT, CW_USEDEFAULT, 400, 200,
        NULL, NULL, hInstance, NULL);

    // 消息循环
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0) > 0) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

效果图:

image

 

请登录后发表评论

    没有回复内容