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
Textproperty does not return any information about the formatting applied to the contents of theRichTextBox. To get the rich text formatting (RTF) codes, use theRtfproperty.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With