指定全部显示不同颜色:
public void SetTextContent(string text, ColorEnum color) { Font font = new Font("微软雅黑", 14, FontStyle.Bold); richTextBox1.Font = font; richTextBox1.Text = text; richTextBox1.ReadOnly = true; layoutControlItem2.Selected = true; SendKeys.Send("{Tab}"); //向活动应用程序发送击键 注意格式:Send("{Tab}");中的{} switch (color) { case ColorEnum.Blue: this.Text = "警告信息"; richTextBox1.ForeColor = Color.Blue; break; case ColorEnum.Red: this.Text = "错误信息"; richTextBox1.ForeColor = Color.Red; break; default: this.Text = "提示信息"; richTextBox1.ForeColor = Color.Black; break; } }
public enum ColorEnum { Black = 0, Blue = 1, Red = 2 }
指定内容中指定文字高亮显示:
private void SetHighlightContent(string text) { ColorEnum color = ColorEnum.Black; string content = string.Empty; ListfindList = new List (); if (text.IndexOf("#Red#", StringComparison.Ordinal) > 0) { color = ColorEnum.Red; var contentArray = text.Split(new[] { "#Red#" }, StringSplitOptions.None); content = contentArray[0]; var findstrs = contentArray[1]; findList = GetFindList(findstrs); } else if (text.IndexOf("#Blue#", StringComparison.Ordinal) > 0) { color = ColorEnum.Blue; var contentArray = text.Split(new[] { "#Blue#" }, StringSplitOptions.None); content = contentArray[0]; var findstrs = contentArray[1]; findList = GetFindList(findstrs); } SetHighlight(content, findList, color); } /// /// 多个要高亮关键词显示的用'&'连接 /// /// ///private List GetFindList(string findstrs) { List findList; if (findstrs.IndexOf("&", StringComparison.Ordinal) > 0) { findList = findstrs.Split('&').ToList(); } else { findList = new List () { findstrs }; } return findList; } private void SetHighlight(string content, List findList, ColorEnum color) { if (!string.IsNullOrEmpty(content)) { if (findList.IsHasRow()) { Font font = new Font("微软雅黑", 14, FontStyle.Bold); richTextBox1.Font = font; richTextBox1.Text = content; this.Text = @"提示信息"; richTextBox1.ReadOnly = true; foreach (var findItem in findList) { List findStrIndexes = GetFindStrIndexes(content, findItem); foreach (var itemindex in findStrIndexes) { richTextBox1.Select(itemindex, findItem.Length); switch (color) { case ColorEnum.Blue: richTextBox1.SelectionColor = Color.Blue; break; case ColorEnum.Red: richTextBox1.SelectionColor = Color.Red; break; } } } richTextBox1.SelectionStart = richTextBox1.Text.Length; //取消选中 layoutControlItem2.Selected = true; SendKeys.Send("{Tab}"); //向活动应用程序发送击键 注意格式:Send("{Tab}");中的{} } else { SetTextContent(content, color); } } } private List GetFindStrIndexes(string content, string findStr) { List result = new List (); int start = 0; while (start < content.Length) { int index = content.IndexOf(findStr, start, StringComparison.Ordinal); if (index >= 0) { result.Add(index); start = index + findStr.Length; } else { break; } } return result; }
参考:
http://www.cnblogs.com/KardelXiao/p/4236045.html (C#)RichTextBox控件 链接跳转设置
http://blog.csdn.net/crazytaliban/article/details/52002657 RichTextBox用法——设置指定字符串的颜色