需求:针对多文本信息显示,我们需要对其内容中的某些关键字或者某行进行高亮显示,并用不同颜色显示。
分析:在C#中,首先要进行多文本信息显示,可以RichTextBox(不要使用TextBox)控件,该控件由自动换行等功能,具体代码如下:
/// <summary> /// 向RichTextBox控件中添加数据 /// </summary> /// <param name="strLineLie">要显示的数据列表,有多少条,就添加多少行</param> private void UpdateRichTextBox(List<string> strLineLie) { if (strLineLie.Count == 0) { richTextBox1.AppendText(" No Input Record Content!"); richTextBox1.SelectAll(); richTextBox1.SelectionAlignment = HorizontalAlignment.Center; richTextBox1.SelectionFont = new System.Drawing.Font(richTextBox1.Font.FontFamily, 11.0f, FontStyle.Italic); richTextBox1.SelectionColor = Color.Gray; return; } //对文本设置对应关键字高亮显示 int index = 0; foreach (string input in strLineLie) { string inputStr = input + " "; this.richTextBox1.AppendText(inputStr); if (input.StartsWith("*"))//注释 { richTextBox1.Select(index, inputStr.Length); richTextBox1.SelectionColor = Color.Green; } else //当行数据类型高亮 { if (input.Split(' ')[0].Length != 0)//每行数据中第一个空格前的关键字高亮 { richTextBox1.Select(index, input.Split(' ')[0].Length); richTextBox1.SelectionColor = Color.Blue; } } index += inputStr.Length; } //设置无效(必填)值高亮显示 HighText("Unknown|Unspecified", this.richTextBox1.Text); } /// <summary> /// 搜索关键字高亮显示 /// </summary> /// <param name="keyStrs"></param> /// <param name="text"></param> private void HighText(string keyStrs,string text) { foreach (string keyStr in keyStrs.Split('|')) { int start = 0, end = text.Length; int index = richTextBox1.Find(keyStr, start, end, RichTextBoxFinds.None); while (index != -1) { richTextBox1.SelectionFont = new System.Drawing.Font(richTextBox1.SelectionFont, FontStyle.Underline); richTextBox1.SelectionColor = Color.Red; start = index + keyStr.Length; index = richTextBox1.Find(keyStr, start, end, RichTextBoxFinds.None); } } }
效果如下: