简体   繁体   中英

How properly use SetMenuItemBitmaps to replace the default bitmap on a menu item?

I'm trying to change the default bitmap on a menu item. Unfortunately, I'm not getting it to work.

The documentation of SetMenuItemBitmaps() states that I should use the GetSystemMetrics() function with the SM_CXMENUCHECK and SM_CYMENUCHECK values to retrieve the default bitmap dimensions. I adjusted the .bmp file to these values, but it is still not working.

I probably have misunderstood something about the SetMenuItemBitmaps() function.

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
        case WM_CREATE:
        SetMenuItemBitmaps(GetMenu(hWnd), ID_RED, MF_BYCOMMAND, LoadBitmap(hInst, L"red.bmp"), LoadBitmap(hInst, L"red.bmp"));
        return 0;
    }
    [...]
}

The menu item with the ID_RED id, whose bitmap I want to change:

图片

You need the HMENU handle of the menu that the red item directly belongs to. You are using the top-level HMENU , but red is a child item of the sub-menu of the color item, which is a child item of the sub-menu of the Menu item, which is a child item of the top-level menu.

Once you have the top-level HMENU , use GetSubMenu() or GetMenuItemInfo() to get the HMENU of the sub-menu for the Menu item, then use that handle to get the HMENU of the sub-menu for the color item, and then finally use that handle to set the bitmaps for the red item.

Also, you are not checking whether LoadBitmap() is returning NULL or not. Even if it is not, you are responsible for destroying the bitmaps when you are done using them. So, even if this code worked, you would be leaking resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM