C# - RichTextBox change color of certain words [duplicate]

Deadly 提交于 2019-12-23 12:18:53

问题


Possible Duplicate:
How to select text from the RichTextBox and then color it?

I don't really have any code to show, because I don't know :(. I have a server that outputs information with tags. For example:

15:44 [INFO] Loaded Properties
15:45 [ERROR] Properties not found

How do I look in the richtextbox and make all ERROR tags red, INFO tags GREEN, etc.?


回答1:


I think this should do what you want:

for(int i=0; i<rtb.Lines.Length; i++) 
{ 
   string text = rtb.Lines[i];
   rtb.Select(rtb.GetFirstCharIndexFromLine(i), text.Length); 
   rtb.SelectionColor = colorForLine(text); 
} 

private Color colorForLine(string line)
{
    if(line.Contains("[INFO]", StringComparison.InvariantCultureIgnoreCase) return Color.Green;
    if(line.Contains("[ERROR]", StringComparison.InvariantCultureIgnoreCase) return Color.Red;

    return Color.Black;
}

Edit: Changed StartsWith to Contains




回答2:


You can do something like:

//will select characters form index 0 to 9
richTextBox1.Select(0, 10);

//will set the characters from 0 to 9 to red
richTextBox1.SelectionColor = Color.Red; 


来源:https://stackoverflow.com/questions/9965264/c-sharp-richtextbox-change-color-of-certain-words

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!