Chủ Nhật, 11 tháng 9, 2016

C# & VB.NET Context Menu Right Click Copy, Cut, Paste Functions


C# .NET for beginners : How to add Context Menu Right Click with Copy, Cut, and Paste Functions in a TextBox or RichTextBox using C# and VB.NET?

Create Context Menu Right in C#

Add Copy, Cut, Paste Function

        void CutAction(object sender, EventArgs e) {
            richTextBox1.Cut();
        }

        void CopyAction(object sender, EventArgs e) {
            Clipboard.SetData(DataFormats.Rtf, richTextBox1.SelectedRtf);
        }

        void PasteAction(object sender, EventArgs e) {
            if (Clipboard.ContainsText(TextDataFormat.Rtf)) {
                richTextBox1.SelectedRtf = Clipboard.GetData(DataFormats.Rtf).ToString();
            }
            richTextBox1.Text = Clipboard.GetText();
        }

Next Add this source code on Event of a TextBox or RichTextBox

        private void richTextBox2_MouseDown(object sender, MouseEventArgs e) {
            if (e.Button == MouseButtons.Right) {
                ContextMenu contextMenu = new System.Windows.Forms.ContextMenu();
                MenuItem menuItem = new MenuItem("Cut");
                menuItem.Click += new EventHandler(CutAction);
                contextMenu.MenuItems.Add(menuItem);
                menuItem = new MenuItem("Copy");
                menuItem.Click += new EventHandler(CopyAction);
                contextMenu.MenuItems.Add(menuItem);
                menuItem = new MenuItem("Paste");
                menuItem.Click += new EventHandler(PasteAction);
                contextMenu.MenuItems.Add(menuItem);
                richTextBox1.ContextMenu = contextMenu;
            }
        }

Create context Menu Right in VB.NET

Add ContextMenuStrip component to your form, then add some items to this ContextMenuStrip like "Copy","CUT" and "Paste".

C# & VB.NET Context Menu Right Click Copy, Cut, Paste Functions

next add this source code :

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

See you next lessons ....

Không có nhận xét nào:

Đăng nhận xét