JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Creating Menus in Code

So far in this chapter, we've designed and built our menu systems at design time, but of course you can create menu systems at run time as well-just create a MainMenu object, add the MenuItem objects you want to it, and assign the MainMenu object to a form's Menu property. Here's an example, CreateMenus on the CD-ROM, that does exactly that. You can see the menu system that this example creates when you click its "Create menu" button in Figure 9.15.

Figure 9.15: Creating menus from code.

Here's the code this example uses to create the menu system you see in Figure 9.15-note that all you really have to do is to create MenuItem objects and use the MenuItems collection's Add method to add them to menus or other menu items:

   Dim mainMenu1 As New MainMenu()

   Dim WithEvents menuItem1 As New MenuItem()
   Dim WithEvents menuItem2 As New MenuItem()
   Dim WithEvents menuItem3 As New MenuItem()
   Dim WithEvents menuItem4 As New MenuItem()

   Private Sub Button1_Click(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles Button1.Click
       menuItem1.Text = "File"
       menuItem2.Text = "New"
       menuItem3.Text = "Text File..."
       menuItem3.Checked = True
       menuItem3.Shortcut = Shortcut.CtrlT
       menuItem4.Text = "Image..."
       menuItem4.Shortcut = Shortcut.CtrlI
       AddHandler menuItem3.Click, AddressOf MenuItem3_Click
       Menu = mainMenu1
   End Sub

   Private Sub MenuItem3_Click(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles menuItem2.Click
       MsgBox("You clicked me!")
   End Sub
Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor