Changes

Jump to: navigation, search

Creating Context Menus in Visual Basic

995 bytes added, 20:02, 25 July 2007
Programming Visual Basic Context Menu Options
Now that we have designed the context menu, and associated it with the form object, we need to write some Visual Basic 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 click on the ''Hide'' menu option to display the Click event procedure code for this menu option. We now need to write some Visual Basic code to call the ''Hide()'' method of the ''MyTextBox'' object as follows:
 
<pre>
Private Sub HideToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles HideToolStripMenuItem.Click
 
MyTextBox.Hide()
 
End Sub
</pre>
 
Similarly, the ''Click'' event of the ''Show'' menu option can be implemented to call the ''Show()'' method of the ''MyTextBox'' object. Double click on the ''Show'' item of the context menu in the form to display the event procedure and add the call to the ''Show()'' method as follows:
 
<pre>
Private Sub ShowToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles ShowToolStripMenuItem.Click
 
MyTextBox.Show()
 
End Sub
</pre>
 
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 will disappear from the form. Right click again and select ''Show'' to once again display the TextBox:
 
[[Image:Exampl.jpg]]

Navigation menu