Answer the question
In order to leave comments, you need to log in
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;
}
private void richInputChains_TextChanged(object sender, EventArgs e)
{
richInputChains.SelectionBackColor = System.Drawing.SystemColors.Window;
}
richInputChains.SelectAll();
richInputChains.SelectionBackColor = System.Drawing.SystemColors.Window;
richInputChains.DeselectAll();
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question