title: Clear SelectionBackColor from text in RichTextBox
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/3282384/richtextbox-syntax-highlighting-in-real-time-disabling-the-repaint">RichTextBox syntax highlighting in real time--Disabling the repaint</a>  </p>
  </blockquote>
  
  
  
  <p>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.</p>
  
  <p>I've already tried two methods of clearing the BackColor from the previous text before applying it to the new words:</p>
  
  <ul>
  <li>Selecting all the text and setting the SelectionBackColor to the Controls BackColor.</li>
  <li>Saving the text to string then putting it back to RichTextBox to clear it's formatting.</li>
  </ul>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>Waiting for your thoughts. Thanks in advance.</p>
  
  <p>Edit: You can see below the method I'm using for the first example I mentioned above (selecting all).</p>
  
  <pre><code>private void ClearSelection(RichTextBox rtb)
  {
      if (rtb.Text.Length &gt; 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);
      }
  }
  </code></pre>
  
  <p>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.</p>
  
  <p><strong>Edit2:</strong> For those interested, the solution at <a href="https://stackoverflow.com/questions/1268009/reset-rtf-in-richtextbox">Reset RTF in RichTextBox?</a> 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.</p>