Software Development

Create shortcut menus for forms in VB.NET using ContextMenuStrip

In order to implement shortcut menus for a form, you can add the VB.NET ContextMenuStrip control to your form. Irina Medvinskaya explains how to use this control.

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

        MsgBox("Open")

    End Sub

Private Sub CloseToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CloseToolStripMenuItem.Click

        MsgBox("Close")

    End Sub

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!

3 comments
ChuckSomerville
ChuckSomerville

As is usually the case, there's a tool for this in VB6 as well. You build the menu with the same tools you use to build "regular" menu bar menus, and invoke it with the PopupMenu method. See the VB6 help index - look for "context menu" and read the item entitled "Displaying Pop-up Menus" for the details. There are sample code snippets. Chuck Somerville Dayton Ohio

Editor's Picks