Reputation: 65
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);
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;
}
I've also tried to refer to this but, I don't think it helps me to solve my case here.
Other than that, just to confirm that my richTextBox1
's SelectionStart
and SelectionLength
were okay, I've even referred to these: ref1, ref2, and ref3.
May I know any other workarounds for this please? Or, were there anything inside my codes that I've missed?
Upvotes: 1
Views: 184
Reputation: 65
Based on comment by @Jimi:
I just need to change the codes in my richTextBox1
's KeyDown
event handler to:
if(richTextBox1.SelectionBackColor != richTextBox1.BackColor)
{
richTextBox1.SelectionBackColor = richTextBox1.BackColor;
}
Thanks!
Upvotes: 1