JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Drawing Menu Items Yourself

Well, your new menu system looks good, but it's just not right. Wouldn't it be much nicer if you could draw people's faces instead of just text?

You can, if that's what you want. To show how this works, take a look at the DrawMenuItem example on the CD-ROM. In this example, I'm drawing an ellipse in a menu item, as you see in Figure 9.14.

Figure 9.14: Drawing a menu item.

Here's how you do it—you first set the menu item's OwnerDraw property to True. Next, you add code to the menu item's MeasureItem event to let Visual Basic know how big you want to make this item when displayed. To pass this information back to Visual Basic, you are passed an object of the MeasureItemEventArgs, and you set this object's ItemHeight and ItemWidth properties in pixels, like this:

Private Sub MenuItem2_MeasureItem(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.MeasureItemEventArgs) _
    Handles MenuItem2.MeasureItem
    e.ItemHeight = 20
    e.ItemWidth = 100
End Sub

Next, you actually draw the item with a Graphics object passed to you in the menu item's DrawItem event. In this case, I'll do that by creating a black pen object to draw with and by drawing an ellipse this way. Note in particular that the boundaries that you're supposed to draw inside are passed to you as a Bounds object (you can use the Height and Width properties of this object to get more information):

Private Sub MenuItem2_DrawItem(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.DrawItemEventArgs) _
    Handles MenuItem2.DrawItem
    Dim pen As New Pen(Color.Black)
    e.Graphics.DrawEllipse(pen, e.Bounds)
End Sub

And, of course, you can handle other events as before for this menu item, such as the Click event:

Private Sub MenuItem2_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
    Handles MenuItem2.Click
    MsgBox("You clicked item 1")
End Sub
Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor