0

将文本文件导入我的 Windows 窗体应用程序富文本框后,我现在想添加搜索功能。是否可以有多个 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();
4

1 回答 1

0

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

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);
于 2012-09-20T21:44:18.353 回答