How to copy the text in 开发者_运维百科a RichTextBox along with its formatting to a wordpad or webbrowser?
Just like with copying plain text, you would use the Clipboard.SetText
method. This clears the current contents of the Windows clipboard and adds the specified text to it.
To copy formatted text, you need to use the overload of that method that accepts a TextDataFormat
parameter. That allows you to specify the format of the text that you wish to copy to the clipboard. In this case, you would specify TextDataFormat.Rtf
, or text consisting of rich text format data.
Of course, for this to work, you will also have to use the Rtf
property of the RichTextBox
control to extract its text with RTF formatting. You cannot use the regular Text
property because it does not include the RTF formatting information. As the documentation warns:
The
Text
property does not return any information about the formatting applied to the contents of theRichTextBox
. To get the rich text formatting (RTF) codes, use theRtf
property.
Sample code:
' Get the text from your rich text box
Dim textContents As String = myRichTextBox.Rtf
' Copy the text to the clipboard
Clipboard.SetText(textContents, TextDataFormat.Rtf)
And once the text is on the clipboard, you (or the user of your application) can paste it wherever you like. To paste the text programmatically, you will use the Clipboard.GetText
method that also accepts a TextDataFormat
parameter. For example:
' Verify that the clipboard contains text
If (Clipboard.ContainsText(TextDataFormat.Rtf)) Then
' Paste the text contained on the clipboard into a DIFFERENT RichTextBox
myOtherRichTextBox.Rtf = Clipboard.GetText(TextDataFormat.Rtf)
End If
I had a similar situation where I was copying from my VB .net application and had tried \r\n, \r, \n, vbCrLf, Chr(13), Chr(10), Chr(13) & Chr(10), etc. The new lines would appear if I pasted into Word or Wordpad, but not into Notepad. Finally I used ControlChars.NewLine where I had been using vbCrLf, and it worked. So, to summarize: Clipboard.SetText("This is one line" & ControlChars.Newline & "and this bad boy is the second.") And that works correctly. Hope it works for you!
I used this simple event handlers (which use the built-in copy/paste methods of the richtextbox) to avoid checking for TextDataFormat:
private void mnuCopy_Click(object sender, EventArgs e)
{
txtRichtext.Copy();
}
private void mnuPaste_Click(object sender, EventArgs e)
{
txtRichtext.Paste();
}
This is a better solution (based on this answer):
var dto = new DataObject();
dto.SetText(richTextBox.SelectedRtf, TextDataFormat.Rtf);
//Since notepad sux and doesn't understand \n,
//we need to fix it replacing by Environment.NewLine (\r\n)
string unformattedText = richTextBox.SelectedText.Replace("\n", Environment.NewLine);
dto.SetText(unformattedText, TextDataFormat.UnicodeText);
Clipboard.Clear();
Clipboard.SetDataObject(dto);
精彩评论