Welcome Guest!
Create Account | Login
Locator+ Code:

Search:
FTPOnline
Channels Conferences Resources Hot Topics Partner Sites Magazines About FTP RSS 2.0 Feed

Free Trial Issue of Visual Studio Magazine

email article
printer friendly


Add Icons to Your Menus
by Andrew Barfield

Level: Intermediate

January 2003 Issue

Technology Toolbox: VB.NET, GDI+

Menu items' OwnerDraw property and events let you leverage the power of GDI+ in dropdown and context menus. Menu icons help users associate menu items and their equivalent commands quickly. With a little creativity, you can build your own Favorites menu or emulate the Windows Start menu, for example.

ADVERTISEMENT

Begin by creating a Windows application and adding a MainMenu from the Visual Studio toolbox. Add a top-level menu item such as &File to it and fill it in with &New, &Open, and so on. Change the OwnerDraw property of each menu item except File to True in the Properties window. This tells the OS you'll lay out and draw your items.

Use a comma-delimited method to specify each menu item's text label and the icon to display. For example, change the &New menu item's text to &New,New. The text before the comma will be drawn as the menu text, and the text after the comma is the item's icon name in your resource file. When your code measures and draws your menu items, the menu labels will split at the comma and be used separately.

If you ran your application now, you'd see the File item on the menu bar, but no items would appear in the dropdown menu, and the dropdown menu would be the wrong size. You must use the MeasureItem event to specify the width and height for each item in your menu(s). Change to the code editor in Visual Studio and select the first OwnerDraw menu item (for instance, New) in the Class Name combo box. Then select the MeasureItem event in the Method Name combo box. This creates the MeasureItem event you'll use for all the menu items. Add its name to the handles list for the other OwnerDraw menu items:

Private Sub Menu_MeasureItem(...) Handles _
   File_New.MeasureItem, File_Open.MeasureItem, _
   File_Save.MeasureItem, _
   File_SaveAs.MeasureItem, _
   File_PageSetup.MeasureItem, _
   File_Print.MeasureItem, _
   File_Exit.MeasureItem, _
   File_Sep1.MeasureItem, File_Sep2.MeasureItem

Examine the code inside the MeasureItem event:

Dim ThisMenuItem As MenuItem = Sender
Dim ThisMenuItem_Strings As String() = _
   ThisMenuItem.Text.Split(",")

Dim TextSize As SizeF = _
   e.Graphics.MeasureString(_
   ThisMenuItem_Strings(0).Replace("&", ""), _
   SystemInformation.MenuFont)

e.ItemWidth = TextSize.Width + 30

If ThisMenuItem.Text = "-" Then
   e.ItemHeight = 3
Else
   e.ItemHeight = 22
End If


Back to top














Java Pro | Visual Studio Magazine | Windows Server System Magazine
.NET Magazine | Enterprise Architect | XML & Web Services Magazine
VSLive! | Thunder Lizard Events | Discussions | Newsletters | FTP Home