Programmatically Creating Menus Menus

220 2. In the Properties window, find the ContextMenu property, and click the arrow of the drop-down list associated with it. 3. The drop-down list displays the ContextMenu objects that are defined on the current form. Choose the desired one. The same effect can be achieved in code by assigning the ContextMenu object to the ContextMenu property of a control or form, like this: Somewhere within the definition of a Form class. Me.Button1.ContextMenu = Me.ContextMenu1

5.5.2 Programmatically Creating Menus

Main menus and context menus can be instantiated and populated directly in code. Ex am ple 5- 2 shows how to create a simple main menu having File and Edit items, with the File item having an Exit item. Compile it from the command line with this command: vbc filename.vb r:System.dll,System.Drawing.dll,System.Windows.Forms.dll t:winexe The code in Ex am ple 5- 2 is similar to the code that would be created by the Windows Forms Designer if its visual menu editor were used to create this menu. The essential steps are: 1. Declare a MainMenu object to represent the menu. 2. Declare a MenuItem object for each menu item. 3. Instantiate the MainMenu object and all the MenuItem objects. 4. Set the properties of the MenuItem objects such as the Text property as desired. 5. Add the top-level MenuItem objects to the MenuItems collection of the MainMenu object, then add the lower-level MenuItem objects to the MenuItems collection of the MenuItem object under which they should appear. Example 5-2. Creating a main menu in code Imports System.Drawing Imports System.Windows.Forms Module modMain System.STAThreadAttribute Public Sub Main System.Threading.Thread.CurrentThread.ApartmentState = _ System.Threading.ApartmentState.STA System.Windows.Forms.Application.RunNew Form1 End Sub End Module Public Class Form1 Inherits Form Declare the main menu component. Private myMenu As MainMenu Declare the menu items that will be in the menu. Use the WithEvents keyword so that event handlers can be added later. Private WithEvents mnuFile As MenuItem Private WithEvents mnuFileExit As MenuItem Private WithEvents mnuEdit As MenuItem Public Sub New Instantiate the menu objects. 221 myMenu = New MainMenu mnuFile = New MenuItem mnuFileExit = New MenuItem mnuEdit = New MenuItem Set the properties of the menu items. mnuFile.Text = File mnuFileExit.Text = Exit mnuEdit.Text = Edit Connect the menu items to each other and to the main menu. mnuFile.MenuItems.AddmnuFileExit myMenu.MenuItems.AddmnuFile myMenu.MenuItems.AddmnuEdit Connect the main menu to the form. Me.Menu = myMenu End Sub End Class

5.5.3 Handling Menu Events