如何在RichTextBox中改变多个字符串的颜色以及字体

目标:传入目标富文本框以及需要查找的字符串,如果文本框中存在字符串,则改变其颜色和字体

可能因为这个问题比较简单,在网上找了很久,也没有一个好的方法。少有的一些方法,也只是改变第一个找到的字符串的颜色和字体。

网上找不到现成的答案只好去翻微软的开发文档,最好,找到的RichTextBox的这么一个方法:

public int Find(
	string str,
	int start,
	RichTextBoxFinds options
)

官方介绍是:在对搜索应用特定选项的情况下,在 RichTextBox 控件的文本中搜索位于控件内特定位置的字符串

看它的官方示例代码:
public int FindMyText(string text, int start)
{
   // Initialize the return value to false by default.
   int returnValue = -1;

   // Ensure that a search string has been specified and a valid start point.
   if (text.Length > 0 && start >= 0) 
   {
      // Obtain the location of the search string in richTextBox1.
      int indexToText = richTextBox1.Find(text, start, RichTextBoxFinds.MatchCase);
      // Determine whether the text was found in richTextBox1.
      if(indexToText >= 0)
      {
         returnValue = indexToText;
      }
   }

   return returnValue;
}

也就是说,其中的start参数是我们要查找的起始点,我们可以用递归的方法,在下一次调用这个方法的时候传入上一次执行的结果+1;而options参数的值是一些枚举,说明了查找的方式,取值有如下一些:

  None 定位搜索文本的所有实例,而不论在搜索中找到的实例是否是全字。
  WholeWord 仅定位是全字的搜索文本的实例。
  MatchCase 仅定位大小写正确的搜索文本的实例。
  NoHighlight 如果找到搜索文本,不突出显示它。
  Reverse 搜索在控件文档的结尾处开始,并搜索到文档的开头。

最终代码如下:
 
   public static void changeStrColorFont(RichTextBox rtBox, string str,Color color,Font font)
        {
            int pos=0;
            while (true)
            {
                pos = rtBox.Find(str, pos, RichTextBoxFinds.WholeWord);
                if (pos == -1)
                    break;
                rtBox.SelectionStart = pos;
                rtBox.SelectionLength = str.Length;
                rtBox.SelectionColor = color;
                rtBox.SelectionFont = font;
                pos = pos + 1;
            }
        }

经过验证,可以实现想要的功能

原文地址:https://www.cnblogs.com/HIT-LYT/p/4289752.html