c# 将某个字的颜色改变
WinForm
使用richTextBox.SelectionColor = Color; 来设置当前选中文本的颜色。
.SelectionStart和.SelectionLength可以设置选择文本的开始位置和长度。
下面这个方法可以更改指定关键字的颜色
public void ChangeKeyColor(RichTextBox rBox, string key, Color color) {
Regex regex = new Regex(key);
//找出内容中所有的要替换的关键字
MatchCollection collection = regex.Matches(rBox.Text);
//对所有的要替换颜色的关键字逐个替换颜色
foreach (Match match in collection) {
//开始位置、长度、颜色缺一不可
rBox.SelectionStart = match.Index;
rBox.SelectionLength = key.Length;
rBox.SelectionColor = color;
}
}
WPF
private void button_Click(object sender, RoutedEventArgs e) {
//改颜色的内容
string word = "11";
//TextPointer tp1 = rBox1.CaretPosition;
//TextPointer tp2 = rBox1.Document.ContentEnd;
rBox1.AppendText("11223311445511\n");
TextPointer tp1;
TextPointer tp2;
while (true) {
tp1 = FindWordFromPosition(rBox1.CaretPosition, word);
if (tp1 == null) { break; }
tp2 = tp1.GetPositionAtOffset(word.Length);
rBox1.Selection.Select(tp1, tp2);
rBox1.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
};
}
// This method will search for a specified word (string) starting at a specified position.
TextPointer FindWordFromPosition(TextPointer position, string word) {
while (position != null) {
if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text) {
string textRun = position.GetTextInRun(LogicalDirection.Forward);
// Find the starting index of any substring that matches "word".
int indexInRun = textRun.IndexOf(word);
if (indexInRun >= 0) {
position = position.GetPositionAtOffset(indexInRun);
break;
}
} else
position = position.GetNextContextPosition(LogicalDirection.Forward);
}
// position will be null if "word" is not found.
return position;
}