A second type of menu system that you may wish to add to your Visual Basic applications is a context menu. Context menus are hidden from view, only appearing when the user right-clicks on the form or control with which the context menu is associated.
A context menu is a menu system that you can attach to a form or control to provide users with easy access to common commands or options made available by your application.
The following procedure outlines the steps involved in setting up a context menu.
Double-click on the ContextMenuStrip control located in the Toolbox to add it to the component tray.
Add menu items to it by keying in text on top of the Type Here text, as demonstrated in Figure 4.24.
Double-click on each of the menu items in the context list and add your program code, as demonstrated below. For example, you might add the following statement to the Click event for the first context menu:
Private Sub ExecuteCommand1ToolStripMenuItem_Click(ByVal sender _ As System.Object, ByVal e As System.EventArgs) Handles ExecuteCommand1ToolStripMenuItem.Click MessageBox.Show("Command 1 should execute now.") End Sub
Similarly, you might add the following code to the Click event for the second context menu item:
Private Sub ExecuteCommand2ToolStripMenuItem_Click(ByVal sender _ As System.Object, ByVal e As System. EventArgs) _ Handles ExecuteCommand2ToolStripMenuItem.Click MessageBox.Show("Command 2 should execute now.") End Sub
Finally, you could assign the following code to the Click event for the third context menu item as shown below.
Private Sub ExecuteCommand3ToolStripMenuItem_Click(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles ExecuteCommand3ToolStripMenuItem.Click MessageBox.Show("Command 3 should execute now.") End Sub
Select the control for which you created the context menu and set its ContextMenuStrip property equal to the name of the context menu that you just created.
Figure 4.24: Configuring the menu items for a context menu.
Once you have finished configuring the form or control's ContextMenuStrip property, you can run your application and access the ContextMenu by right-clicking on the form or control, as demonstrated in Figure 4.25.
Figure 4.25: Examining the contents of Button control's associated context menu.