Saturday 14 September 2013

VB.Net - ContextMenuStrip Control

The ContextMenuStrip control represents a shortcut menu that pops up over controls, usually when you right click them. They appear in context of some specific controls, so are called context menus. For example, Cut, Copy or Paste options.
This control is associated a context menu with other menu items by setting that menu item's ContextMenuStrip property to the ContextMenuStrip control you designed.
Context menu items can also be disabled, hidden or deleted. You can also show a context menu with the help of the Show method of the ContextMenuStrip control.
The following diagram shows adding a ContextMenuStrip control on the form:
VB.Net ContextMenuStrip Control

Properties of the ContextMenuStrip Control

The following are some of the commonly used properties of the ContextMenuStrip control:
S.NPropertyDescription
1SourceControlGets the last control that displayed the ContextMenuStrip control.

Example

In this example, let us add a content menu with the menu items Cut, Copy and Paste.
Take the following steps:
  1. Drag and drop or double click on a ControlMenuStrip control, to add it to the form.
  2. Add the menu items, Cut, Copy and Paste to it.
  3. Add a RichTextBox control on the form.
  4. Set the ContextMenuStrip property of the rich text box to ContextMenuStrip1 using the properties window.
  5. Double the menu items and add following codes in the Click event of these menus:
Private Sub CutToolStripMenuItem_Click(sender As Object, e As EventArgs) _
Handles CutToolStripMenuItem.Click
   RichTextBox1.Cut()
End Sub

Private Sub CopyToolStripMenuItem_Click(sender As Object, e As EventArgs) _
Handles CopyToolStripMenuItem.Click
   RichTextBox1.Copy()
End Sub

Private Sub PasteToolStripMenuItem_Click(sender As Object, e As EventArgs) _
Handles PasteToolStripMenuItem.Click
   RichTextBox1.Paste()
End Sub
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show following window:
Context Menu Strip Example
Enter some text in the rich text box, select it and right-click to get the context menu appear:
Context Menu Strip Example
Now you can select any menu items and perform cut, copy or paste on the text box.

No comments:

Post a Comment