Home > Net >  RichTextBox does not copy new lines to the clipboard
RichTextBox does not copy new lines to the clipboard

Time:01-24

In the code, I generate formatted text into a WPF RichTextBox. I use Environment.NewLine to insert line break. Everything looks fine. However, when I copy the contents of a RichTextBox to Clipboard (using RichTextBox context menu) and paste it into Word or WordPad, line breaks disappear. However, if I paste the contents of the clipboard as plain text (e.g. into notepad), the new lines do not disappear. Don't know why this is so?

Update:

// _richTextBox is my object RichTextBox
var doc = _richTextBox.Document;
var paragraph = doc.Blocks.FirstOrDefault() as Paragraph;
if (paragraph == null) return;

var span = new Span();
span.Inlines.Add(new Underline(new Run($"Header: {Environment.NewLine}")));
span.Inlines.Add(new Run("Text content"));

paragraph.Inlines.Add(span);

CodePudding user response:

The solution was simple in the end. I didn't notice that there was a LineBreak object. If you use LineBreak instead of \r\n (Environment.NewLine), then line break will work in both plain text and formatted text.

  •  Tags:  
  • Related