Recipe 4.19. Creating Shortcut Menus


Problem

You want to display a custom shortcut menu to users when they right-click on a form or one of its controls.

Solution

Sample code folder: Chapter 04\ShortcutMenus

Use the ContextMenuStrip control to design a shortcut menu (also called a context or pop-up menu) that you can attach to the controls (or form) of your choice.

Create a new Windows Forms application, and add a ContextMenuStrip control named MainShortcutMenu to the form. When you select that control, it adds a temporary standard menu to the control that you can use to add new menu items (see Figure 4-20).

Figure 4-20. Shortcut menus in design mode


Add two menu items to this shortcut menu:

  • A menu item named MenuHello, using Say Hello for its Text property

  • A menu item named MenuGoodbye, using Say Goodbye for its Text property

Select the form itself, and then change its ContextMenuStrip property to MainShortcutMenu.

Now, add the following source code to the form's code template:

 Private Sub MenuHello_Click(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MenuHello.Click    MsgBox("Hello") End Sub Private Sub MenuGoodbye_Click(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles MenuGoodbye.Click    MsgBox("Goodbye") End Sub 

Run the program, and right-click on the form. The shortcut menu will present itself, as shown in Figure 4-21. Clicking on the items puts up a message box saying "Hello" or "Goodbye."

Figure 4-21. The shortcut menu in use


Discussion

Each form and control includes a ContextMenuStrip property that you can assign to any ContextMenuStrip control included with your form. You can create as many shortcut menus as needed for your controls.

Some controls, such as the TextBox control, already include default shortcut menus. If you wish to enhance one of these menus, you will have to design your own menu from scratch and provide your own implementations for menu items previously found in that control's shortcut menu.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net