Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying text along with its formatting from a RichTextBox

How to copy the text in a RichTextBox along with its formatting to a wordpad or webbrowser?

like image 205
SpongeBob SquarePants Avatar asked Feb 05 '11 05:02

SpongeBob SquarePants


2 Answers

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 the RichTextBox. To get the rich text formatting (RTF) codes, use the Rtf 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
like image 147
Cody Gray Avatar answered Sep 17 '22 18:09

Cody Gray


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!

like image 42
UncleSmokinJoe Avatar answered Sep 18 '22 18:09

UncleSmokinJoe