Search In Site

25 June, 2013

Adding And Deleting Menu Items At Runtime in Vb

Adding And Deleting Menu Items At Runtime
We’ve all seen menus that change as a program runs, and that can be a sophisticated effect. It’s also impressive if the menu can change in response to user input (for example, adding a new item with the caption _Create Progname.exe_, where Progname is the name given the program). You can add this capability to your program in Visual Basic. Here, we’ll just add new items Item 1, Item 2, and so onto the File menu with the user clicks a button. We start by designing our menu system, giving it a File menu with two items: New and Items.

The Items item is actually a placeholder for the items we_ll add to the File menu. Make this item into a control array by giving it an index, 0, in the Index box. This item is just a placeholder we don’t want it to be visible before the user adds items to this menu so set its Visible property to False.

Now add a button to the program, and give it a Click event-handling function:

Private Sub Command1_Click()
End Sub


We’ll keep track of the items in the File menu with a variable named intItemCount, which we increment each time the button is clicked:

Private Sub Command1_Click()
Static intItemCount
intItemCount = intItemCount + 1
...
End Sub


To add a new item to the Items control array, we use Load():

Private Sub Command1_Click()
Static intItemCount
intItemCount = intItemCount + 1
Load mnuFileItems(intItemCount)
...
End Sub


Finally, we set the caption of the item to indicate what its item number is, and make it visible:

Private Sub Command1_Click()
Static intItemCount
intItemCount = intItemCount + 1
Load mnuFileItems(intItemCount)
mnuFileItems(intItemCount).Caption = "Item " & intItemCount
mnuFileItems(intItemCount).Visible = True
End Sub


You can also add a Click event handler to the Items menu item (because it’s not visible in the menu bar, find mnuFileItems in the code window and add the event handler to it there). This event handler is passed the index of the clicked item in the control array, so we can indicate to the user which item he has clicked:

Private Sub mnuFileItems_Click(Index As Integer)
MsgBox ("You clicked item " + Str(Index))
End Sub


To remove items from the menu, just use Unload() statement like this (and make sure you adjust the total item count):

Unload mnuFileItems(intItemCount)

0 comments:

Post a Comment

Dear Visitors All The Tricks And Hacks Posted Here Are Only For Knowledge Purpose.Don't Use These for Illegal Operations.

 
Twitter Bird Gadget