To demonstrate just how flexible a menu can be in VB .NET, we're going to create a main menu with a caption Great Web Sites and one menu item using the About.COM logo as a graphic and custom text using theForte font, naturally, since Visual Basic is our Forte! The single menu item lists the single great web site you need to know: About Visual Basic!
As MacDonald notes in his book, there are basically three steps to accomplish this:
- Set the OwnerDraw property to True for each menu item where you plan to code your own custom text and graphics.
- Handle the MeasureItem event.
- Handle the DrawItem event.
Once you set the OwnerDraw property to True, VB .NET expects that code will exist in your program to actually create any text and graphics in the menu item. The menu item will still be displayed, but it will be a tiny empty box. Here's the code that does the trick. Lines are continued to make it fit the web page here, and notice that must be changed to the actual path to the graphic on your computer:
Private Sub mnuTopGreatSite_MeasureItem( _
ByVal sender As Object, _
ByVal e As _
System.Windows.Forms.MeasureItemEventArgs) _
Handles mnuTopGreatSite.MeasureItem
Dim mnuItem As MenuItem = CType(sender, MenuItem)
Dim MenuFont As New Font("Forte", 12)
e.ItemHeight = _
e.Graphics.MeasureString(mnuItem.Text, _
MenuFont).Height + 25
e.ItemWidth = _
e.Graphics.MeasureString(mnuItem.Text, _
MenuFont).Width + 130
End Sub
Private Sub mnuTopGreatSite_DrawItem( _
ByVal sender As Object, _
ByVal e As _
System.Windows.Forms.DrawItemEventArgs) _
Handles mnuTopGreatSite.DrawItem
Dim mnuItem As MenuItem = CType(sender, MenuItem)
Dim mnuFont As New Font("Forte", 12)
Dim mnuImage As Image = _
Image.FromFile("\about.jpg")
e.Graphics.DrawImage(mnuImage, _
e.Bounds.Left, e.Bounds.Top)
e.Graphics.DrawString( _
mnuItem.Text, mnuFont, _
New SolidBrush(Color.Red), _
e.Bounds.Left + 135, e.Bounds.Top + 18)
End Sub
If the OwnerDraw property of a menu item set to true, the event MeasureItem is raised before the menu is drawn to allow for the size of the menu item to be specified. We create a font here just to make it available for measurements. We add some space since we know that a graphic will be used when the menu item is actually drawn.
The DrawItem event is raised when a request is made to actually draw the menu item. There are two parts to drawing the menu item in our code: draw the graphic (e.Graphics.DrawImage) and draw the text (e.Graphics.DrawString).
So when you're creating a great "main course" system, Visual Basic .NET will give you a menu to match.
First page >
Entering the Event Code for the Menu > Page
1,
2,
3,
4,
5