C# - 富文本框改变特定单词的颜色

6

可能是重复问题:
如何在RichTextBox中选择文本并进行着色?

我没有任何代码可以展示,因为我不知道 :(。 我有一个带标签的服务器输出信息。 例如:

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

我怎样在richtextbox中查找并使所有的ERROR标签显示为红色,INFO标签显示为绿色?


2
我建议作为重复的帖子的被接受答案似乎是实现你想要的非常好的方法。 - David Hall
谢谢,但正则表达式无效 - 命名空间是什么? - Alex Ogden
1
System.Text.RegularExpressions; http://msdn.microsoft.com/zh-cn/library/system.text.regularexpressions.aspx - David Hall
右键单击方法,选择解决。VS 将会自动为你弹出它。 - Tony Hopkinson
2个回答

2
我认为这应该是您想要的内容:

我认为这应该符合您的需求:

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;
}

编辑:StartsWith更改为Contains


@AlexOgden 尝试使用 Contains 而不是 StartsWith - L.B
尝试在colorForLine中设置断点,看看条件是否被触发。 - aKzenT

0
你可以这样做:
//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; 

其他答案已经表明,它是SelectionColor而不是SelectionColour - L.B
@EddardStark - 或者只是众所周知的英语 - Matt Wilko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接