So after seeing the typing test Dani so kindly made the other day and put on the site I decided to kill some time writing a simple application to practice my typing on.

I have a RTB containing the text which I'm highlighting as I go type letters to show the next one. However using the code:

rtbText.SelectionBackColor = Color.Red;
rtbText.SelectionStart = RTBSelectBegin;
rtbText.SelectionLength = RTBSelectLength;

For some reason I have to call this twice to see any response? The letter does not highlight on first call, but an immediate second call of the same highlight method containing these three lines creates the desired result.

Any ideas as to why this behaviour occurs?

The order might have something to do with it. Setting the SelectionBackColor applies the color to the currently selected text. So the text you select after it won't be affected.

If that works for you, great. If not though, could you post some more code (ie Is it a handler/called from a handler? Where is RTBSelectBegin and RTBSelectLength being set from?)?

Sadly your suggestion did not resolve the issue :(

RTBSelectBegin is declared at the top with a value of 0.
RTBSelectLength is also declared at the top with a value of 1.

The call is used within the following:

private void FormKeyPress(object sender, KeyPressEventArgs e)
        {
            if (rtbText.SelectedText == e.KeyChar.ToString())
            {
                rtbText.SelectAll();
                rtbText.SelectionBackColor = this.BackColor;
                rtbText.DeselectAll();

                RTBSelectBegin++;

                rtbText.SelectionStart = RTBSelectBegin;
                rtbText.SelectionLength = RTBSelectLength;
                rtbText.SelectionBackColor = Color.Red;
                rtbText.SelectionStart = RTBSelectBegin;
                rtbText.SelectionLength = RTBSelectLength;
                rtbText.SelectionBackColor = Color.Red;
            }
            if (rtbText.SelectedText == "\n" && e.KeyChar.ToString() == "/r")
            {
                rtbText.SelectAll();
                rtbText.SelectionBackColor = this.BackColor;
                rtbText.DeselectAll();

                RTBSelectBegin++;

                rtbText.SelectionStart = RTBSelectBegin;
                rtbText.SelectionLength = RTBSelectLength;
                rtbText.SelectionBackColor = Color.Red;
                rtbText.SelectionStart = RTBSelectBegin;
                rtbText.SelectionLength = RTBSelectLength;
                rtbText.SelectionBackColor = Color.Red;
            }
        }

This fires everytime a key is pressed within the form, checks if the key matches the currently highlighted letter in the richtextbox and then moves the highlight along by one character.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.