Search code examples
c#winformsrichtextbox

When pasting text from the Clipboard into a RichTextBox, the new text is not colored in the RichTextBox ForeColor


I created a ToolStripMenuItem for the RichTextBox. In its Click event, I'm pasting into the RichTextBox some text from the Clipboard.

The problem is that in the Form Designer the ForeColor of the RichTextBox is set to Color.Yellow, but if the text in the Clipboard contains different colors, some sections of the text won't be visible all, because the BackColor of the RichTextBox is black.
I want to select the pasted text and color it in yellow.

This is the event where I paste the text:

private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
    // Handle the Paste event
    richTextBox1.Paste();

    // Set the desired formatting (e.g., yellow color) for the pasted text
    richTextBox1.SelectionColor = Color.Yellow;
}

I tried to add the line:

richTextBox1.SelectionColor = Color.Yellow;

but it didn't solve anything.

Here is a screenshot example of text I paste in the RichTextBox. The text in the Clipboard is partially colored in blue and brown.
The brown color is swallowed in the black background and the blue is hard to see. I want it all to be in yellow.

colors

How can I change my code so that no matter what text I paste into the RichTextBox, it will be colored using the RichTextBox ForeColor?


Solution

  • When you paste text into a RichTextBox, the caret is moved to the end of the new text.
    Setting the SelectionColor does nothing, since nothing is selected.
    If any formatting - that the Control understands - is applied to the pasted text, that format is preserved (e.g., if you paste text copied from the Visual Studio editor, MS Word, etc.)

    You can store the caret position before the new text is pasted in, then subtract that position from the current, which points to the end of the pasted text, to determine the length of the pasted text.

    Then select that chunk only, to change its color. For example:

    var previousStartPosition = richTextBox1.SelectionStart;
    
    richTextBox1.Paste();
    
    var newTextLength = richTextBox1.SelectionStart - previousStartPosition;
    richTextBox1.Select(previousStartPosition, newTextLength);
    richTextBox1.SelectionColor = Color.Yellow; // Or richTextBox1.ForeColor