Using a Bitmap as a Menu Item

Windows lets you use bitmaps as menu items. There are two ways to do this:

When you insert or append a new menu item, specify that you want to use a bitmap instead of text for that item.

Use the ModifyMenu function to change an existing item so that it appears as a bitmap instead of text.

You cannot specify a bitmap as a menu item in the .RC file.

The following example loads a bitmap named Apples, then uses the ModifyMenu function to replace the text of the Apples command with a bitmap image of an apple.

HMENU hMenu;

HBITMAP hBitmap;

.

.

.

1 hBitmap = LoadBitmap (hInstance, “Apples”);

2 hMenu = GetMenu(hWnd);

ModifyMenu (hMenu,

3 IDM_APPLES, /* item to replace */

4 MF_BYCOMMAND | MF_BITMAP,

5 IDM_APPLES, /* Menu ID of new item */

6 (LPSTR) MAKELONG (hBitmap, 0))

In this example:

1 The LoadBitmap function loads the bitmap from the file and returns a handle to the bitmap, saved in the hBitmap variable.
2 The GetMenu function retrieves the handle of the current window's menu, and places it in the variable hMenu. This variable is then passed as the first parameter of the ModifyMenu function, which specifies which menu to change.
3 The second parameter of the ModifyMenu function, in this case set to IDM_APPLES, specifies the menu item to modify.
4 The third parameter specifies how to make the changes. MF_BYCOMMAND tells Windows that we are specifying the item to change by its menu ID rather than by its position. MF_BITMAP indicates that the new item will be a bitmap rather than text.
5 The fourth parameter of the ModifyMenu function, set to IDM_APPLES, specifies the new menu ID for the item we are modifying. In this example, the menu ID does not change.
6 The new bitmap handle must be passed as the low-order word of the fifth parameter of ModifyMenu. The MAKELONG utility combines the 16-bit handle with a 16-bit constant to make the 32-bit argument. Casting the parameter to an LPSTR prevents the compiler from issuing a warning, since the compiler expects this parameter to be a string.