I
I
int02h2011-09-24 15:09:54
C++ / C#
int02h, 2011-09-24 15:09:54

Reset Formatting in RichTextBox (WinForms)

I appeal to you, dear habra community, with my possibly lamer question. The form has a RichTextBox called richInputChains. The task is to color each of its lines in red or green, depending on the results of a certain check. I do it like this:

foreach(string line in richInputChains.Lines)
{
  bool accepted = SomeCheck(line);
  richInputChains.SelectionStart = pos;
  richInputChains.SelectionLength = line.Length;
  richInputChains.SelectionBackColor = (accepted) ? Color.Green : Color.Red;
  pos += line.Length + 1;
}

Everything works great. But now I can’t figure out how to reset all this coloring now. I do this in the TextChange event handlers for richInputChains:
private void richInputChains_TextChanged(object sender, EventArgs e)
{
  richInputChains.SelectionBackColor = System.Drawing.SystemColors.Window;
}

However, when I start changing the text, the old coloring remains. What to do? Where am I wrong?

Type method:
richInputChains.SelectAll();
richInputChains.SelectionBackColor = System.Drawing.SystemColors.Window;
richInputChains.DeselectAll();

and similar ones are unsuccessful, since they do not allow you to safely enter new text (after all, the action takes place in the text change handler), because the user clicked at a certain position in the text, and after the specified transformation, the caret is moved to the beginning of the text.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dzuba, 2011-09-25
@int02h

A counter question: why not remember the caret position, or rather, the selection (SelectionStart, SelectionLength) before SelectAll() and restore this case instead of DeselectAll()?
At the same time, in order to avoid unnecessary triggering of the TextChanged event, it may make sense to enter the appropriate bulk. Just in case.
It's just that I don't use a RichTextBox and so I'm not sure if the TextChanged event will be fired again when we change the color of the text in the TextChanged event handler.
It will turn out like this:

private bool isTextChangedHandlerRunning;

private void richInputChains_TextChanged(object sender, EventArgs e)
{
  if (isTextChangedHandlerRunning)
    return;

  isTextChangedHandlerRunning = true;
  int saveStart = richInputChains.SelectionStart;
  int saveLength = richInputChains.SelectionLength;

  richInputChains.SelectAll();
  richInputChains.SelectionBackColor = System.Drawing.SystemColors.Window;
  
  richInputChains.SelectionStart = saveStart;
  richInputChains.SelectionLength = saveLength;
  isTextChangedHandlerRunning = false;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question