设置多个textbox.SelectionStart值,以突​​出显示搜索到的单词

时间:2012-09-20 21:27:51

标签: c# selection

将文本文件导入我的Windows窗体应用程序RTF框后,我现在想要添加搜索功能。是否可以有多个SelectionStart值? SelectionLength将会看到同一个词。

        string textfield = TextField.Text;
        string searchword = searchbox.Text;
        int found=0;
        TextField.SelectionLength = searchword.Length;
        TextField.SelectionBackColor = Color.LightBlue;

        for (int y = 0; y < textfield.Length; y++)//Goes through whole string
        {
            if (searchword[0] == textfield[y])//Looks for first character
            {
                for (int x = 0; x < searchword.Length; x++)//Checks if rest of  characters match
                {
                    if (searchword[x] == textfield[y + x])
                    {
                        found++;
                    }
                    else
                        break;
                }
            }

            if (found == searchword.Length)
            {
                TextField.SelectionStart = y;//////Want to have multiple of these
            }
            found=0;
        }
        TextField.Focus();

1 个答案:

答案 0 :(得分:1)

不,你不能。但是,您可以更改所选文本的背景颜色。首先选择一个单词。然后这样做

foreach (Match match in matches) {
    richTextBox.SelectionStart = match.Index;
    richTextBox.SelectionLength = match.Length;
    richTextBox.SelectionBackColor = Colors.Yellow;
}

要清除所有标记,只需选择整个文本并将背面颜色设置为白色(假设您没有使用背面颜色)。

在示例中,我假设您使用的是Regex。你会找到单词:

string pattern = String.Format(@"\b{0}\b", Regex.Escape(wordToFind));
MatchCollection matches = Regex.Matches(richTextBox.Text, pattern);