WinForms RichTextBox: how to perform a formatting on TextChanged?

岁酱吖の 提交于 2019-12-11 06:47:14

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/1456953/winforms-richtextbox-how-to-perform-a-formatting-on-textchanged

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!