Add ContextMenu with Cut,Copy and paste options to Textbox in vb.net

 

In this article we learn that how to add Context menu to Textbox with Cut, Copy and paste options on runtime, this article also show that how to add context menu to any control at runtime that has these options:

Cut : Moves the current selection in the text box to the Clipboard,This method will only cut text from the text box if text is selected in the control. You can use this method, instead of using the Clipboard class, to copy text in the text box and move it to the Clipboard.

Copy: copy the selected text to clipboard.

paste: paste the text that has clipboard.

following example requires one windows form with mulitline textbox control named ‘TextBox1′.

Example

Private Sub Form1_Load(ByVal sender As System.Object, _
  1. ByVal e As System.EventArgs) Handles MyBase.Load
  2.     AddContextMenu()
  3. End Sub
  1.     Private Sub AddContextMenu()
  2.  
  3.         Dim Contextmenu1 As New ContextMenu
  4.  
  5.         Dim menuItem1Cut As New MenuItem("Cut")
  6.         AddHandler menuItem1Cut.Click, AddressOf menuItem1Cut_Click
  7.  
  8.         Dim menuItem2Copy As New MenuItem("Copy")
  9.         AddHandler menuItem2Copy.Click, AddressOf menuItem2Copy_Click
  10.  
  11.         Dim menuItem3Paste As New MenuItem("Paste")
  12.         AddHandler menuItem3Paste.Click, AddressOf menuItem3Paste_Click
  13.  
  14.         Contextmenu1.MenuItems.Add(menuItem1Cut)
  15.         Contextmenu1.MenuItems.Add(menuItem2Copy)
  16.         Contextmenu1.MenuItems.Add(menuItem3Paste)
  17.  
  18.         TextBox1.ContextMenu = Contextmenu1
  19.  
  20.     End Sub
  1. Private Sub menuItem1Cut_Click()
  2.         TextBox1.Cut()
  3.     End Sub
  4.     Private Sub menuItem2Copy_Click()
  5.         TextBox1.Copy()
  6.     End Sub
  7.     Private Sub menuItem3Paste_Click()
  8.         TextBox1.Paste()
  9.     End Sub

we can use this code with RichtextBox control also with some modification.

Published by

Hirendra Sisodiya

Programmer at PSPL. Can be found on Google Plus.

  • Michael Smith

    Great Info….Thanks