JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Creating Menus

So how do you actually create menus in Visual Basic? The simplest way to do so is at design time, because all you have to do is to add a MainMenu control from the toolbox to a Windows form. When you do so, the MainMenu control appears in the component tray under the form designer, as you see in Figure 9.11. (In fact, it would be more proper to call this a MainMenu component, because it does not inherit the Control class, and it appears in the component tray, but Visual Basic calls this a MainMenu control.)

Click To expand
Figure 9.11: Adding a menu system to a form.

Note the text "Type Here" in Figure 9.11. To create a new menu, you just have to double-click that text to open a text box which you can use to enter the caption for menus and menu items. When you're creating a new menu item, "Type Here" boxes appear in all the other places you can enter text. To create a new menu in the menu bar, add a submenu to the current menu item, and so on, as you see in Figure 9.12, where I'm editing the menu system in the Menus example on the CD-ROM. Using this control is intuitive and easy—all you have to do is to enter text in the "Type Here" boxes and double-click the resulting menus and menu items to add code to their Click events in the corresponding code designer. To drag menu items around, repositioning them after you've given them a caption, just use the mouse.

Click To expand
Figure 9.12: Adding menu items to a form.

How do you make the menu items you've added to a menu system active? For each menu and menu item you add at design time, Visual Basic creates a MenuItem object, and you can handle its Click event. For example, the last menu item in the File menu is the Exit item in the Menus project. It turns out that this item is MenuItem4 in this example, so when I double-click it in the form designer, its Click event opens in the code designer, and I can use the End statement to end the program:

Private Sub MenuItem4_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles MenuItem4.Click
End Sub

Now when the user clicks the Exit menu item at run time, the program will terminate.

Previous Section Next Section

JavaScript Editor Free JavaScript Editor     JavaScript Editor