Creating Menus in Code using VB.net

By: Emiley J. Viewed: 153221 times    

This example creates a menu system - 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
       menuItem2.MenuItems.Add(menuItem3)
       menuItem2.MenuItems.Add(menuItem4)
       AddHandler menuItem3.Click, AddressOf MenuItem3_Click
       menuItem1.MenuItems.Add(menuItem2)
       mainMenu1.MenuItems.Add(menuItem1)
       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

Most Viewed Articles (in VB.net )

Latest Articles (in VB.net)

Comment on this tutorial