C #: paste RTF into RichTextBox but keep staining and formatting (ie: bold, underline, etc.)

advertisements

Is it possible to paste text into a Rich Text Box, while keeping the font being used in the Rich Text Box for the pasted content ?

In other words, I'd like to copy something from Word that is formated (i.e: a text that uses a font X and is underlined and in blue), and then paste it in my RichTextBox.

I would like the pasted content to have the same font as that of my RichTextBox but keep its original coloring and underlining.

Is such a thing possible ?

I use winforms.

Thanks


This is not possible out of the box. But you can do something like this:

public void SpecialPaste()
{
    var helperRichTextBox = new RichTextBox();
    helperRichTextBox.Paste();
    for(int i=0;i<helperRichTextBox.TextLength;++i)
    {
        helperRichTextBox.SelectionStart = i;
        helperRichTextBox.SelectionLength = 1;
        helperRichTextBox.SelectionFont = new Font(richTextBox1.SelectionFont.FontFamily, richTextBox1.SelectionFont.Size,helperRichTextBox.SelectionFont.Style);
    }

    richTextBox1.SelectedRtf = helperRichTextBox.Rtf;
}

This changes the font of the pasted RTF to that of the character preceding the caret position at the time of the paste.
I assume that will get problematic pretty fast, if the text you paste is large(er). Additionally, this can be optimized in a way, that it sets the font only once for all characters in a row with the same base font as Hans suggests.

Update:
Here is the optimized version, that sets the font for a connected set of characters with the same original font:

public void SpecialPaste()
{
    var helperRichTextBox = new RichTextBox();
    helperRichTextBox.Paste();
    helperRichTextBox.SelectionStart = 0;
    helperRichTextBox.SelectionLength = 1;

    Font lastFont = helperRichTextBox.SelectionFont;
    int lastFontChange = 0;
    for (int i = 0; i < helperRichTextBox.TextLength; ++i)
    {
        helperRichTextBox.SelectionStart = i;
        helperRichTextBox.SelectionLength = 1;
        if (!helperRichTextBox.SelectionFont.Equals(lastFont))
        {
            lastFont = helperRichTextBox.SelectionFont;
            helperRichTextBox.SelectionStart = lastFontChange;
            helperRichTextBox.SelectionLength = i - lastFontChange;
            helperRichTextBox.SelectionFont = new Font(richTextBox1.SelectionFont.FontFamily, richTextBox1.SelectionFont.Size, helperRichTextBox.SelectionFont.Style);
            lastFontChange = i;
        }
    }
    helperRichTextBox.SelectionStart = helperRichTextBox.TextLength-1;
    helperRichTextBox.SelectionLength = 1;
    helperRichTextBox.SelectionFont = new Font(richTextBox1.Font.FontFamily, richTextBox1.Font.Size, helperRichTextBox.SelectionFont.Style);

    richTextBox1.SelectedRtf = helperRichTextBox.Rtf;
}

It's pretty ugly code and I am sure it can be improved and cleaned. But it does what it should.