最近用C#编写了一个在RichTextBox中查找字符串并标记的方法
string find = item.SubItems[1].Text;//find为想要查找的字符串
int index = richTextBoxContent.Find(find, RichTextBoxFinds.WholeWord);//调用find方法,并设置区分全字匹配
int startPos = index;
int nextIndex = 0;
while (nextIndex != startPos)//循环查找字符串,并用蓝色加粗12号Times New Roman标记之
{
richTextBoxContent.SelectionStart = index;
richTextBoxContent.SelectionLength = find.Length;
richTextBoxContent.SelectionColor = Color.Blue;
richTextBoxContent.SelectionFont = new Font("Times New Roman", (float)12,FontStyle.Bold);
richTextBoxContent.Focus();
nextIndex = richTextBoxContent.Find(find, index + find.Length, RichTextBoxFinds.WholeWord);
if (nextIndex == -1)//若查到文件末尾,则充值nextIndex为初始位置的值,使其达到初始位置,顺利结束循环,否则会有异常。
nextIndex = startPos;
index = nextIndex;
}