为什么当使用文本框搜索文本和颜色的结果程序冻结



我有这样一个类:

private class Utility
        {
            public static void HighlightText(RichTextBox myRtb, string word, Color color)
            {
                int s_start = myRtb.SelectionStart, startIndex = 0, index;
                while ((index = myRtb.Text.IndexOf(word, startIndex)) != -1)
                {
                    myRtb.Select(index, word.Length);
                    myRtb.SelectionColor = color;
                    startIndex = index + word.Length;
                }
                myRtb.SelectionStart = s_start;
                myRtb.SelectionLength = 0;
                myRtb.SelectionColor = Color.Black;
            }
        }

然后使用:

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            Utility.HighlightText(richTextBox1, textBox1.Text, Color.Red);
        }

第一次当我点击文本框中的东西,它会在richTextBox中的文本着色。但是,当我删除文本框中的文本,它是空的程序冻结,我使用了一个断点,它似乎卡在while循环中的实用程序类在HighlightText。

我想做的是:

  1. 在textBox中键入text free也删除文本并再次键入新文本,它将在richTextBox中实时突出显示文本。

  2. 仅当我在textBox中键入单词时,然后在richTextBox中突出显示/颜色。现在如果我输入SHARE这个词它会高亮/上色所有包含字母s或以字母s开头的地方

您只需要考虑要突出显示的单词为空的情况,在这种情况下,您只需跳过循环。否则,它将无限循环,因为startIndex永远不会增加,因为你一直在给它加零(word.Length)。

那么就在循环周围添加一个条件,像这样:

public static void HighlightText(RichTextBox myRtb, string word, Color color)
{
    int s_start = myRtb.SelectionStart, startIndex = 0, index;
    if (!string.IsNullOrEmpty(word)) {
        while ((index = myRtb.Text.IndexOf(word, startIndex)) != -1)
        {
            myRtb.Select(index, word.Length);
            myRtb.SelectionColor = color;
            startIndex = index + word.Length;
        }
    }
    myRtb.SelectionStart = s_start;
    myRtb.SelectionLength = 0;
    myRtb.SelectionColor = Color.Black;
}

编辑:我还应该添加,当word为空时,则mytf . text。IndexOf(word, startIndex)方法调用将始终返回startIndex的值。它永远不会返回-1。在这种情况下,更有理由跳过循环。

不深入讨论细节,最简单的解决方案是将try-catch块添加到您的方法中,如下所示:

            public static void HighlightText(RichTextBox myRtb, string word, Color color)
            {
                try{
int s_start = myRtb.SelectionStart, startIndex = 0, index;
                while ((index = myRtb.Text.IndexOf(word, startIndex)) != -1)
                {
                    myRtb.Select(index, word.Length);
                    myRtb.SelectionColor = color;
                    startIndex = index + word.Length;
                }
                myRtb.SelectionStart = s_start;
                myRtb.SelectionLength = 0;
                myRtb.SelectionColor = Color.Black;
} catch{}
            }

希望这能有所帮助。最好的祝福,

最新更新