不为 C++ 中的工具栏加载自定义位图

Not loading custom bitmaps for toolbar in C++

我正在开发一个 WINAPI 应用程序,我使用 CreateWindowEx().

创建了一个工具栏,如您所知,为工具栏按钮加载自定义图标,您应该在资源文件中指定包含图标列表的位图,并将其加入工具栏
(通过使用 tbab.nID = IDB_LIST;)。但它不起作用!

resource.h:

#define IDB_LIST 101


resource.rc:

#include "resource.h"
IDB_LIST BITMAP "list.bmp"


main.cpp:

            TBBUTTON tbb[1];
            TBADDBITMAP tbab;

            tbab.hInst = g_hInst;
            tbab.nID = IDB_LIST;

            hToolBar = CreateWindowEx(TBSTYLE_EX_MIXEDBUTTONS, TOOLBARCLASSNAME, NULL, WS_CHILD | WS_VISIBLE | TBSTYLE_TOOLTIPS, 0, 0, 0, 0,
                hWnd, (HMENU)IDC_MAIN_TOOL, g_hInst, NULL);

            SendMessage(hToolBar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);
            SendMessage(hToolBar, TB_ADDBITMAP, (WPARAM)1, (LPARAM)&tbab);
            SendMessage(hToolBar, TB_SETMAXTEXTROWS, 0, 0);

            ZeroMemory(&tbb, sizeof(tbb));
            tbb[0].iBitmap = 0;
            tbb[0].fsState = TBSTATE_ENABLED;
            tbb[0].fsStyle = TBSTYLE_BUTTON;
            tbb[0].idCommand = ID_FILE_NEW;
            tbb[0].iString = (INT_PTR)"Create a new file";

            SendMessage(hToolBar, TB_ADDBUTTONS, sizeof(tbb)/sizeof(TBBUTTON), (LPARAM)&tbb);

我用了另一种方式加载位图。

修改后的代码(仅提供自定义位图部分):

HWND CreateSimpleToolbar(HWND hWnd)
{
    TBBUTTON tbb[1];
    TBADDBITMAP tbab;

    const int bitmapSize = 32;
    const int ImageListID = 0;

    hToolBar = CreateWindowEx(TBSTYLE_EX_MIXEDBUTTONS, TOOLBARCLASSNAME, NULL, WS_CHILD | WS_VISIBLE | TBSTYLE_TOOLTIPS | TBSTYLE_WRAPABLE, 0, 0, 0, 0,
        hWnd, NULL, g_hInst, NULL);
    HBITMAP bitmap = (HBITMAP)LoadImage((HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE), MAKEINTRESOURCE(IDB_LIST), IMAGE_BITMAP, 32, 32, NULL);

    SendMessage(hToolBar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);

    ZeroMemory(&tbb, sizeof(tbb));
    tbb[0].iBitmap = 0;
    tbb[0].fsState = TBSTATE_ENABLED;
    tbb[0].fsStyle = TBSTYLE_BUTTON;
    tbb[0].idCommand = ID_FILE_NEW;
    tbb[0].iString = (INT_PTR)L"Create a new file";

    g_hImageList = ImageList_Create(bitmapSize, bitmapSize,   // Dimensions of individual bitmaps.
        ILC_COLOR24 | ILC_MASK,   // Ensures transparent background.
        1, 0);
    ImageList_Add(g_hImageList, bitmap, NULL);

    SendMessage(hToolBar, TB_SETIMAGELIST,
        (WPARAM)ImageListID,
        (LPARAM)g_hImageList);

    SendMessage(hToolBar, TB_ADDBUTTONS, sizeof(tbb) / sizeof(TBBUTTON), (LPARAM)&tbb);

    SendMessage(hToolBar, TB_AUTOSIZE, 0, 0);
    return hToolBar;
}

调试:

我主要用ImageList_Add.

Adds an image or images to an image list.

参考:How to use custom icons for toolbars in winapi programming

Create an image list using ImageList_Create(), add your BMP image to it using ImageList_Add() or ImageList_ReplaceIcon(), associate it with the toolbar using TB_SETIMAGELIST, and then you can set tbb[0].iBitmap to the BMP's index within the image list.

不过可以肯定的是,图片ID是没问题的。我把BMP图片加载到资源文件中,然后加载图片就成功了