Cheeso
Cheeso

Reputation: 192467

WinForms RichTextBox: how to perform a formatting on TextChanged?

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.

Upvotes: 1

Views: 913

Answers (1)

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

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.

Upvotes: 3

Related Questions