I have searched around on the net but I cannot find a method of copying/cutting/pasting selected text from a RichTextBox
.
Even MSDN does not have an answer. The code they provide does not work: Copy()
only appears to work on TextBoxes, not RichTextBoxes.
If you're using .NET 3.0 and above you can always use Clipboard.SetText()
I found it useful to use the Clipboard when I want everything in the richTextBox without having to select everything first or when I need to change the string:
string text = "Summary:" + Environment.NewLine + this.richTextBoxSummary.Text;
Clipboard.SetText(text);
if I copy this method:
Clipboard.SetText(richTextBox1.SelectedRtf, TextDataFormat.Rtf);
i can't paste to notepad
if I copy this method:
Clipboard.SetText(richTextBox1.SelectedText, TextDataFormat.UnicodeText);
it's working in Word and notepad, but inserts in word without formating
richTextBox1.Copy();
working in Word and notepad, but I can't modify string value.
How can I copy normally formatted string in Clipboard?
P.S. I found
DataObject dto = new DataObject();
dto.SetText(mesrtf, TextDataFormat.Rtf);
dto.SetText(mes, TextDataFormat.UnicodeText);
Clipboard.Clear();
Clipboard.SetDataObject(dto);
it works
richTextBox1.SelectAll();
richTextBox1.Copy();
/*
selects all the txt in the box and preserves formatting when u paste it again into notepad
*/
VB.NET code (Support both formatted and plain text)
Cut
Private Sub CutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CutToolStripMenuItem.Click
Try
If RichTextBox1.SelectedText <> "" Then
Clipboard.SetData(DataFormats.Rtf,RichTextBox1.SelectedRtf)
RichTextBox1.SelectedRtf = ""
Else
MsgBox("No item is selected to cut", MsgBoxStyle.Information, "Cut")
End If
Catch ex As Exception
MsgBox("Can't cut the selected item", MsgBoxStyle.Critical, "Cut")
End Try
End Sub
Copy
Private Sub CopyToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CopyToolStripMenuItem.Click
Try
If RichTextBox1.SelectedText <> "" Then
Clipboard.SetData(DataFormats.Rtf,RichTextBox1.SelectedRtf)
Else
MsgBox("No item is selected to copy", MsgBoxStyle.Information, "Copy")
End If
Catch ex As Exception
MsgBox("Can't copy the selected item", MsgBoxStyle.Critical, "Copy")
End Try
End Sub
Paste
Private Sub PasteToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PasteToolStripMenuItem.Click
Try
If Clipboard.ContainsText(TextDataFormat.Rtf) Then
RichTextBox1.SelectedRtf = Clipboard.GetData(DataFormats.Rtf).ToString()
ElseIf Clipboard.ContainsText(TextDataFormat.Text) Then
RichTextBox1.SelectedText = Clipboard.GetData(DataFormats.Text).ToString()
Else
MsgBox("Clipboard is not contained with the valid text format ", MsgBoxStyle.Information, "Paste")
End If
Catch ex As Exception
MsgBox("Can't paste the item", MsgBoxStyle.Critical, "Paste")
End Try
End Sub
in wpf just
richTextBox1.Copy();
richTextBox1.Paste();
来源:https://stackoverflow.com/questions/4064125/copy-selected-text-from-richtextbox