In order to implement shortcut menus for a form, you can add the VB.NET ContextMenuStrip control to your form. In the design mode, the control will appear on the bottom of the form. When you click the control, you can add menu items to it.
There are two items in my example: Open and Close. Set the form’s ContextMenuStrip property to ContextMenuStrip1 and add the following code:
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
Private Sub CloseToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CloseToolStripMenuItem.Click
In the code, I create the menu items under the ContextMenuStrip1 control; I also link this menu control to the Form. Then, I add code to the click of each separate menu item available in the ContextMenuStrip1 control.
When you run the example, right-click on the form, you will see the menu options I defined: Open and Close. If you click the Open item, it will display the “Open” message box; if you click the Close item, it will display the “Close” message box.
Note: In my example, I created the shortcut menus for a form. The same method will work for a control on the form if you set the control’s ContextMenuStrip property to ContextMenuStrip1.
Irina Medvinskaya has been involved in technology since 1996. She has an MBA from Pace University and works as a project manager at Citigroup.
Get Visual Basic tips in your inbox
Advance your scripting skills to the next level with TechRepublic’s free Visual Basic newsletter, delivered each Friday. Automatically subscribe today!