的WinForms RichTextBox的:如何在框TextChanged进行格式化?如何在、WinForms、RichTextBox、TextChanged

2023-09-06 08:30:48 作者:想哭就要笑

我有,我想重新格式化一个RichTextBox时的RichTextBox中的内容发生变化。我有一个TextChanged事件处理程序。

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

重新格式化(改变所选区域的颜色)触发TextChanged事件。它导致TextChange情况下,重新格式化,TextChange事件的永无止境的循环,重新格式化,等等。

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.

推荐答案

您可以有一个布尔标志,指示是否已经在框TextChanged 处理里面:

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

这样,您创建一个循环停止其他框TextChanged 事件。

 
精彩推荐
图片推荐