Providing Context Menus for Your UI Objects

Much of the ease of use of Windows 95 comes from the fact thatits user interface objects have their own context menus, whichcan be accessed through a simple right-click of the mouse. Inkeeping with this theme, you can provide context menus for theinterface objects in your applications too. Making and respondingto a context menu is a pretty straightforward and simple process.These steps illustrate how this is done using a standard listbox called lstSample as the interface object:

1. Define the context menu. The context menu is really a standardmenu item which has submenu items just like your Help menu itemwould. Unlike your Help menu item, however, a context menu itemwill have its Visible property set to False so that the user neversees it on the form’s menu. For this example, open a new formand use the Menu Editor to make a new top-level menu item andgive it the name mnu_lstSampleContextMenu. The caption will neverbe seen by the user, but should be something descriptive thatreminds you what the menu is used for, such as “Context MenuFor lstSample Control.” Set the Visible check box for thismenu item to False. Now, define the sub-menu items that will appearwhen the user right-clicks on the control: “&Clear,””Clear A&ll,” “&Add Item,” “&RemoveItem,” and so forth.

2. Write the code that will show the context menu when the userright-clicks the control. This is done by invoking VB’s PopupMenumethod in the control’s _MouseDown event. Here is a code sample:

 Private Sub lstSample_MouseDown(Button _        As Integer, Shift As Integer, X As _        Single, Y As Single)        ' if the user right clicked on         ' control then show the popup menu         ' for this control        If Button And vbRightButton Then _                PopupMenu _                mnu_lstSampleContextMenuEnd Sub

3. All that is left to do is to write the code in the click eventfor each of the context menu’s submenu items. The PopupMenu methodcan also do neat things like bold a menu item, place the menuat a specific location, and so forth. For more information onthe PopupMenu method, see the VB help file.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: