Question

I've written an application that has a richtextbox in it with a black background. Therefore I have to write in it using white text. That all works fine by setting the fore color to white. If I however copy text from Word that is black into my textbox, that text remains black.

I need to change the color of that text. So this is what i've tried so far: (the textbox is named txtMessage)

txtMessage.ForeColor = Color.White;

That doesn't have any effect on the existing black text though.

Then I tried this:

private void txtMessage_TextChanged(object sender, EventArgs e)
    {
        int s = txtMessage.SelectionStart;
        txtMessage.SelectAll();
        txtMessage.SelectionColor = Color.White;
        txtMessage.Select(s, 0);

    }

It in principle works fine but of course every time I edit the text in the textbox (not copying something in there, but simply typing) the whole thing is executed with every letter I type resulting in a flickering ( I guess because all is selected and then deselected every single time).

So does anyone have a suggestion how to fix this elegantly?

Thank you very much.

Was it helpful?

Solution

If you are typing in the box an the colour is set to white, there is no need to run the code.

You only need to run it when you add text that you haven't typed (eg copy/paste from your example).

Therefore, use that code in the TextChanged event, but perform a check before running it as to whether the user has typed the text or added it another way

EDIT: Check the answer to this question: Detecting a paste into a RichTextBox, it might help you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top