Add dynamically menu items at run time in VB 6.0

It is very simple to add menu items at runtime. VB menu items are nothing more than special control arrays. And just as with any control array, if you want to dynamically add menu items at runtime, you must place at least one control on your project at designtime. Once you do so, you can then use the Load command to create new objects. The following code shows an example of how this will work.


For this example, we added an invisible menu item named mnuShortCut to a form, and then added one submenu item to it, named mnuSubItem. We gave this submenu item an index of 0 and set its Caption to "Menu Item 1". 

Private Sub Form_Load()

Dim x As Integer

For x = 1 To 4

    Load mnuSubItem(x)

    mnuSubItem(x).Caption = "Menu Item " & x + 1

    mnuSubItem(x).Visible = True

Next x

End Sub


Private Sub Form_MouseDown(Button As Integer, Shift As Integer, x As Single, Y As Single)

If Button = vbRightButton Then

    Me.PopupMenu mnuShortCut

End If

End Sub


Private Sub mnuSubItem_Click(Index As Integer)

MsgBox Index

End Sub


Notice that to display the shortcut menu, the code initiates the PopupMenu method during the form's MouseDown event. After testing to see if the right mouse button was pushed, the code then calls the shortcut menu, which our code created in the Load() event.

Added on December 29, 2007 Comment