views:

192

answers:

2

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.

A: 

The TextChange event will fire when you change the .Text propery of a RichTextBox, regardless of if it's the user of your program.

It you want to reformat the text, write to the .Rtf property of the control, then that event won't fire.

ParmesanCodice
+2  A: 

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
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