Come back to home page

Put bitmap in menu /API Version/ (Form; Menu; VB.NET)

I am sure we all have developed applications with menus. Right? And obviously, we all use the applications with menus. Take Office for example, or our .NET IDE. What is the difference between the menus of these applications and our menus? These applications have bitmaps in their menus. .NET does not have the facility of putting images in menus by design. How can we achieve this?

There are two ways we can do this:

Code

The first step is to declare the API we are going to use:

Private Declare Sub SetMenuItemBitmaps Lib "user32" (ByVal hMenu As IntPtr, ByVal nPosition As Int32, ByVal _
wFlags As Int32, ByVal hBitmapUnchecked As IntPtr, ByVal hBitmapChecked As IntPtr)


The name explains the use of this function:
SetMenuItemBitmaps

It takes following argumets:

hMenu: Integer Pointer or Handle to the parent menu in which we want to put the image
nPosition: Position of the menu item in parent menu
wFlags: How the position must be taken. Value &H0  - identifier of the menu (we need another API to find this). We will use &H400 because this value tells the function to take the zero based relative position of the menu
hBitmapUnchecked: Handle to the bitmap when menu is unchecked (
menu.Checked=False)
hBitmapChecked: Handle to the bitmap when menu is checked

To get hMenu, we use:  mnuMain.MenuItems(<item_position>).Handle, where mnuMain is the main menu on our form.

The position of all the items within this menu can be given by integers (0,1,2,...)

To get the handle to bitmap we can use the GetHbitmap method of bitmap. This method will not appear in the member list of bitmap object when you put a '.' after the object (I'm talking about intellisense here).

So, here is the code that does it all...

SetMenuItemBitmaps(mnuMain.MenuItems(0).Handle, 0, &H400&, New Bitmap("filenameunchecked.bmp").GetHbitmap(), _
New Bitmap("filenamechecked.bmp").GetHbitmap())

In the above code, we have taken two files - filenameunchecked.bmp and filenamechecked.bmp, one of these bitmaps will appear depending on the value of checked property of the menu in question.

Do you know what this API does? What happens when the checked property is set to True? A check mark appears before the menu and when the property is set to False, the checkmark goes. This API simply replaces the checkmark bitmap with the image we specify.

I recommend that you experiment with the code to get familiar with it. This is pretty simple and very fast (thanks to API).

I will stop here for the sake of brevity. If you need further explanation, please contact me, I will be glad to answer you.

You already know my email address: rahul@coder000.com . You may contact me for your feedback (it gives motivation), suggestions, questions or comments freely.

Happy coding!!