Changes

Jump to: navigation, search

Creating Context Menus in C Sharp

4 bytes added, 20:04, 1 April 2009
no edit summary
[[Image:visual_basic_textbox_context.jpg]]
The purpose of this example is to create a context menu on the form which will contain options to hide and show the ''MyTextBox'' object. From the Visual Studio Toolbox, double click on the ''ContextMenuStrip'' object. The object will be added to the form. You will notice, however, that since the menu is not located at any specific position in the form, it is located in the panel beneath the form. To display the menu in the form, or edit properties of the object, simply click on this instance of the object. With the object selected, change the name to ''TextBoxMenu'' by changing the ''Name'' property in the Properties panel. You will notice also, that a representation of the context appears in the form area:
[[Image:visual_basic_new_context_menu.jpg]]
Add items to the menu simply by typing in the ''Type Here'' fields. Each time you enter a new item a new ''Type Here'' field will appear. To add an item other than a menu option, click on the small down arrow which appears in the text box. It is possible to add ComboBoxes, Separators, TextBoxes and MenuItems to a context menu. With the exception of separators and MenuItems, these items should not be placed in menus because they violate the rules of good GUI design.
Once an item has been added to the menu , right clicking on the item provides a list of properties which may be changed, such as making an item checkable, or disabling an item so that it cannot be selected by the user. It is also possible to define an image to be displayed for the menu option.
To complete this phase of the tutorial, add menu items labeled ''Hide'' and ''Show''.
== Programming C# Context Menu Options ==
Now that we have designed the context menu, and associated it with the form object, we need to write some C# code to cause the ''MyTextBox'' object to hide and show depending on the menu selection. This is achieved by implementing ''Click'' event procedures for the hide and show menu items. In Visual Studio, select the ''TextBoxMenu'' object in the panel beneath the form. Once selected, a representation of the context menu will appear in the form. Douible Double click on the ''Hide'' menu option to display the Click event procedure code for this menu option. We now need to write some C# code to call the ''Hide()'' method of the ''MyTextBox'' object as follows:
<pre>
== Compiling and Running the Application ==
Compile and run the application by pressing the '''F5''' key. Right click anywhere on the form to invoke the context menu and select ''Hide''. The TestBox TextBox will disappear from the form. Right click again and select ''Show'' to once again display the TextBox:
[[Image:c_sharp_context_example_running.jpg]]

Navigation menu