Home > other >  Why is the "RichTextBox.SelectionBackColor" not reverting to default on the new and unsele
Why is the "RichTextBox.SelectionBackColor" not reverting to default on the new and unsele

Time:03-20

I have a RichTextBox. I'm working on changing the SelectionBackColor only of the selected text.

Then, I have a ToolStripMenuItem(let's call it 'buttonA' for now) which is responsible to change the SelectionBackColor of the selected text. The problem I'm facing is after I click buttonA, the background color of the selected text in the RichTextBox can be successfully done. However, when I add some other characters or text right after the changed background color text, it doesn't use the default background color. Instead, it continues to use the same background color as assigned from buttonA, which I don't want to happen.

At first, I thought that my start index and end index of the selected text was problematic. But, I don't think there's any problems in its codes. Below shows the code example:

SolidBrush textBgCol; //a variable to keep color

this.richTextBox1.Select = this.richTextBox1.SelectionStart, this.richTextBox1.SelectionLength;

this.richTextBox1.SelectionBackColor = Color.FromArgb(textBgCol.Color.A, textBgCol.Color.R, textBgCol.Color.G, textBgCol.Color.B);

  1. One of my efforts was to change the SelectionBackColor to default in the KeyDown event of richTextBox1. However, the background color of the new or successive characters and text were still the same as assigned from buttonA. Below shows the code example:
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
    this.richTextBox1.SelectionBackColor = default;
}
  1. I've also tried to refer to theDemo

    Thanks!

  • Related