Possible Duplicate:
RichTextBox syntax highlighting in real time--Disabling the repaint
I'm using a RichTextBox control to find and change the SelectionBackColor property of some words. The words are not fixed so basically the text that has different BackColor varies.
I've already tried two methods of clearing the BackColor from the previous text before applying it to the new words:
- Selecting all the text and setting the SelectionBackColor to the Controls BackColor.
- Saving the text to string then putting it back to RichTextBox to clear it's formatting.
Although both methods work an issue arises when you have a lot of text in the control. For the first method, it becomes clearer that all text gets selected (you can notice it for a few milliseconds), which becomes annoying since this happens in the TextChanges event, so basically every letter that gets removed/added triggers this. As for the second method, it's not that obvious as the first, but since the text is removed and then insert back, the scrolling becomes a bit odd since even after using .ScrollToCaret() the scrollbar isn't exactly were it was before the SelectionBackColor clearing.
It feels like there should be a better way of clearing the existing SelectionBackColor without all these issues. Especially in this case since it has to do the cleaning in the TextChanged event.
Waiting for your thoughts. Thanks in advance.
Edit: You can see below the method I'm using for the first example I mentioned above (selecting all).
private void ClearSelection(RichTextBox rtb)
{
if (rtb.Text.Length > 0)
{
int currentIndex = rtb.SelectionStart;
rtb.SelectAll();
rtb.SelectionBackColor = Color.White;
rtb.SelectionLength = 0;
rtb.SelectionStart = currentIndex;
}
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
if (!_working)
{
ClearSelection(richTextBox1);
}
}
The _working bool is just to make sure that the method doesn't get trigged when the program is changing the colour of certain words so that it will only be trigged when it's the user changing the text.
Edit2: For those interested, the solution at Reset RTF in RichTextBox? seems to do the trick. I would avoid the one that was voted as duplicate (for some odd reason) since it produces more graphical issues.