Doron Muzar Doron Muzar - 25 days ago 14
C# Question

My RichTextBox's cut/copy/paste doesn't cut, copy, or paste

Here's my code:

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

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

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

private void richTextBox2_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{ //click event
//MessageBox.Show("you got it!");
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);

richTextBox2.ContextMenu = contextMenu;
}
}


I have 2 problems:


  • After marking the text in
    richTextbox2
    I need to simulate a right click on the mouse to see the cut paste copy menu.

  • When I click on Copy I can't afterwards paste it anywhere because there is nothing to paste. I didn't test yet the cut and paste options but after doing copy it's not working.


Answer

Remove the Clipboard.Clear();

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

You can also use the Copy() method of a RichTextBox:

void CopyAction(object sender, EventArgs e) {
 richTextBox2.Copy();
}

For paste:

void PasteAction(object sender, EventArgs e) {
   if (Clipboard.ContainsText(TextDataFormat.Rtf)) {
      SendKeys.Send("^v");
   } 
}
Comments