1

I have a RichTextBox that I want to re-format when the contents of the RichTextBox changes. I have a TextChanged event handler.

The re-formatting (changing colors of selected regions) triggers the TextChanged event. It results in a never-ending loop of TextChange event, reformat, TextChange event, reformat, and so on.

How can I distinguish between text changes that result from the app, and text changes that come from the user?

I could check the text length, but not sure that is quite right.

Cheeso
  • 189,189
  • 101
  • 473
  • 713

1 Answers1

3

You can have a bool flag indicating whether you are already inside the TextChanged processing:

private bool _isUpdating = false;
private void Control_TextChanged(object sender, EventArgs e)
{
    if (_isUpdating)
    {
        return;
    }

    try
    {
        _isUpdating = true;
        // do your updates
    }
    finally
    {
        _isUpdating = false;
    }
}

That way you stop the additional TextChanged events from creating a loop.

Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
  • This is good, but keep in mind that _isupdating should be used anywhere the app changes the richtextbox text, not just inside the handler. – xpda Sep 21 '09 at 21:54