可能重複:
How to select text from the RichTextBox and then color it?C# - 某些詞
我真的沒有任何代碼來展示,因爲我不知道:(我。例如:
15:44 [INFO] Loaded Properties
15:45 [ERROR] Properties not found
如何查看richtextbox並使所有錯誤標籤red,信息標籤綠色等?
可能重複:
How to select text from the RichTextBox and then color it?C# - 某些詞
我真的沒有任何代碼來展示,因爲我不知道:(我。例如:
15:44 [INFO] Loaded Properties
15:45 [ERROR] Properties not found
如何查看richtextbox並使所有錯誤標籤red,信息標籤綠色等?
我想這應該做你想要什麼:
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
它不工作:( – 2012-04-01 15:10:33
@AlexOgden嘗試使用'Contains'而不是'StartsWith' – 2012-04-01 15:12:13
嘗試在colorForLine中設置一個斷點並查看條件是否被擊中 – aKzenT 2012-04-01 16:06:10
你可以這樣做:
//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' – 2012-04-01 15:22:19
對不起!英國英語!:) – 2012-04-01 15:25:03
@EddardStark - 或只是英文,因爲它是已知的 – 2014-08-28 10:36:21
對後接受的答案我建議重複看起來是一個很好的方式做你想做的事 – 2012-04-01 14:57:15
謝謝,但正則表達式不起作用 - w帽子的命名空間? – 2012-04-01 15:12:28
System.Text.RegularExpressions; http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.aspx – 2012-04-01 15:14:32