我的RichTextBox的剪切/复制/粘贴不会剪切,复制或粘贴

Dor*_*zar 1 .net c# copy-paste richtextbox winforms

这是我的代码:

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;
    }
} 
Run Code Online (Sandbox Code Playgroud)

我有两个问题:

  • 在标记文本后,richTextbox2我需要模拟右键单击鼠标以查看剪切粘贴复制菜单.
  • 当我点击Copy时,我无法将其粘贴到任何地方,因为没有要粘贴的内容.我没有测试剪切和粘贴选项,但在复制后它无法正常工作.

Kin*_*ing 5

除掉 Clipboard.Clear();

void CopyAction(object sender, EventArgs e) {
  Clipboard.SetData(DataFormats.Rtf, richTextBox2.SelectedRtf);            
}
Run Code Online (Sandbox Code Playgroud)

您还可以使用以下Copy()方法RichTextBox:

void CopyAction(object sender, EventArgs e) {
 richTextBox2.Copy();
}
Run Code Online (Sandbox Code Playgroud)

用于粘贴:

void PasteAction(object sender, EventArgs e) {
   if (Clipboard.ContainsText(TextDataFormat.Rtf)) {
      SendKeys.Send("^v");
   } 
}
Run Code Online (Sandbox Code Playgroud)

  • 打败我吧... -_- (2认同)