Context Menu

Many Windows applications have shortcut menus, which are displayed when the user clicks the right mouse button over the area of the form, or over a control on the form. Figure 11 -9 shows a shortcut menu in Microsoft Word.

.¡J l)tx:uiTH-nl3 H »iIiMidl WchiI

J F*i F-rti Uta hi^: Fjmsi Jo* TjW VvrL.bn, fl*

□ ~ e & ft <? - ■■ -: - - n © ? ?

■b rMu

:= BjW: jrdN-jfflbft.lf

tlx»**

■Ü

ladni r

+

tap 1 fK 1 1,1] se, J" Li* L Co1 "

Figure 11-9: A shortcut menu

Ask the Expert

Figure 11-9: A shortcut menu

Ask the Expert

Question: Should I create a menu using the Menu Designer or do it programmatically? Answer: I recommend using the Menu Designer when you can, simply because it is faster and less prone to error than creating the menu by code. Question: Why would I create a menu programmatically when using the Menu Designer is faster and less prone to error?

Answer: As you progress in Visual Basic .NET and deal with more complex applications, you may need to modify menus dynamically—that is, while the application is running. This is not possible using the Menu Designer; you can only do so programmatically.

Also, creating a menu by code teaches you much more about how a menu works than using the Menu Designer, which hides the details from you.

Shortcut menus also are called context menus, because the particular menu items displayed depend on the context, such as the application state, or where on the form or control the right mouse button was clicked. Indeed, in Visual Basic .NET, the ContextMenu class represents shortcut menus.

Context menus typically are used to combine different menu items from a MainMenu of a form that are useful for the user given the context of the application. For example, you can use a shortcut menu assigned to a TextBox control to provide immediate access to menu items also found in the MainMenu to cut, copy, and paste text, find text, change the text font, and so on. However, a context menu also may contain menu items not found in the form's MainMenu, such as to provide situation-specific commands that are not appropriate for the MainMenu to display.

Creating a Context Menu

As with the MainMenu, you can add a context menu to a Windows form either at design time in the Windows Forms Designer or programmatically at runtime. Either way, creating a menu is a two-step process. You first add a ContextMenu object to your form, and th en you append to it MenuItem objects.

Was this article helpful?

0 0

Post a comment