如何將RichTextBox中的文本及其格式複製到wordpad或webbrowser?從RichTextBox複製文本及其格式
回答
就像複製純文本一樣,您可以使用Clipboard.SetText
method。這將清除Windows剪貼板的當前內容並向其添加指定的文本。
要複製帶格式的文本,您需要使用接受TextDataFormat
參數的overload of that method。這允許您指定要複製到剪貼板的文本的格式。在這種情況下,您將指定TextDataFormat.Rtf
,或者包含富文本格式數據的文本。
當然,爲了達到這個目的,您還必須使用RichTextBox
控件的Rtf
property來提取RTF格式的文本。您不能使用常規Text
property,因爲它不包含RTF格式信息。正如文檔警告:
Text
屬性不會返回任何有關格式應用於RichTextBox
的內容的信息。要獲取富文本格式(RTF)代碼,請使用Rtf
屬性。
示例代碼:
' 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)
而一旦文本是在剪貼板上,您(或您的應用程序的用戶)可以你喜歡的地方粘貼。要以編程方式粘貼文本,您將使用也接受TextDataFormat
參數的Clipboard.GetText
method。例如:
' 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
我也有類似的情況,我從我的VB .NET應用程序複製和曾試圖\ r \ n,\ r,\ n,vbCrLf,CHR(13)CHR(10) ,Chr(13)& Chr(10)等等。如果我粘貼到Word或寫字板中,但不粘貼到記事本中,則會出現新行。最後,我使用了ControlChars.NewLine,我一直使用vbCrLf,並且它工作正常。所以,總結一下: Clipboard.SetText(「這是一行」& ControlChars.Newline &「這個壞男孩是第二個。」) 而且這個工作正常。希望對你有幫助!
這是一個更好的解決方案(基於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);
我用這個簡單的事件處理程序(使用RichTextBox中的內置的複製/粘貼的方法),以避免檢查TextDataFormat:
private void mnuCopy_Click(object sender, EventArgs e)
{
txtRichtext.Copy();
}
private void mnuPaste_Click(object sender, EventArgs e)
{
txtRichtext.Paste();
}
它也會複製RichTextBox中的圖像,我該如何將它轉換爲html? – 2011-02-05 07:03:28