如何更改 richTextBox 中特定字符串的颜色

How to change color for specific string in richTextBox

我正在尝试将特定字符串的颜色更改为 richTextBox,将其中的文本文档打开为现有字符串或通过 richTextBox 添加以保存其他文本并保持黑色,除了具体线路。

我参加了 richTextBox_TextChanged 活动,但对我来说效果不佳。它可以很好地更改特定字符串的文本并使其他文本保持黑色,但在所有情况下我都遇到同样的两个问题,首先:

如果我将来自 richTextBox 的特定彩色红色字符串添加到与其他单词或字符合并的文本中,例如:

如果文本文件内容是:

some string
some string
red string

如果我添加类似的内容:

some string
some string
xred string 

或:

some string
some string
red stringx

结果变成第二个,如果我添加另一个字符串等于 "red string":

some string
some string
red stringx        // << This line remains red
red string         // << and this does not changes and remains black

还有一个问题,如果我在richTextBox中的红色字符串之后写文字,那么在写作阶段后面的所有文字也会变成红色。

例如必须为红色的字符串是:

string Str = "red string";

这样:

   Color aColor = Color.FromName(Str.Split(' ')[0]);
   if (richTextBox1.Text.Contains(Str) && aColor != Color.Red)
   {
       richTextBox1.Select(richTextBox1.Text.IndexOf(Str), Str.Length);
       richTextBox1.SelectionColor = Color.Red;
   }

或者这样:

   Color aColor = Color.FromName(Str.Split(' ')[0]);
   if (richTextBox1.Text.Contains(Str) && aColor != Color.Red)
   {
       richTextBox1.Find(Str); 
       richTextBox1.SelectionColor = Color.Red;
   }

或者这种方式,它可以包含列出的字符串,如果需要的话,可以为每种不同的颜色改变颜色 string[] words = { "specword1", "specword2" };,但在这种情况下,只是显示为不同的方式来做到这一点,具有相同且只需要的值从上面看,空 string[] words:

  string[] words = { "" };
  Color[] colors = { Color.Red };
  for (int i = 0; i < words.Length; i++)
  {
        string word = words[i];
        Color color = colors[i];
     {
        richTextBox1.Find(Str);
        richTextBox1.SelectionColor = color;
     }
  }

我在所有尝试中都遇到了同样的两个问题,如果我将它与 Form1_Load 一起使用,它不会对颜色进行任何更改。

所以我想知道这个案例有什么解决方案,我只想到一件事,但不确定它是否是解决这个问题的正确方法:

我不知道怎么做,但不知何故无法编辑红色字符串,它在文本文档中总是在单独的行上,同时不允许手写或粘贴到richTextBox

无论如何,如果它可以帮助解决第一个问题,似乎它无助于避免更改红色字符串后的后续文本的颜色。

inside richTextBox_TextChanged 比较时检查整行文本

string str = "red string";
for(int i=0; i<richTextBox1.Lines.Length; i++) 
{ 
   string text = richTextBox1.Lines[i];
   richTextBox1.Select(richTextBox1.GetFirstCharIndexFromLine(i), text.Length); 
   if(text ==str)
   {
    richTextBox1.SelectionColor = Color.Red;
   }else
   {
     richTextBox1.SelectionColor = Color.Black;
   }    
 }

对于多种颜色,我会使用字典

var dictionary = new Dictionary<string, System.Drawing.Color>();
    dictionary.Add("red color", System.Drawing.Color.Red);
    dictionary.Add("Blue color", System.Drawing.Color.Blue);
//as above example you can use for loop and get each line of rich textbox
string linefromTextBox = "Blue color";
//then check that line contain of of text in the dictionaly 
if (dictionary.ContainsKey(linefromTextBox))
{
   // if key found then you can get the color as below
   // asign this as SelectionColor 
   //before that you need to Select the line from rich text box as above example
   var color = dictionary[linefromTextBox];
}