C#的richtextbox中,输入文字时,如何使不同的字符串显示不同的颜色?

C#的richtextbox中,输入文字时,如何使不同的字符串显示不同的颜色?

就像上面两张图片一样,不同字符串不同颜色。拜托了,谢谢!!!

C# richTextBox显示不同颜色文字
#region 日志记录、支持其他线程访问
public delegate void LogAppendDelegate(Color color, string text);
/// <summary>
/// 追加显示文本
/// </summary>
/// <param name="color">文本颜色</param>
/// <param name="text">显示文本</param>
public void LogAppend(Color color, string text)
{
richTextBoxRemote.AppendText("/n");
richTextBoxRemote.SelectionColor = color;
richTextBoxRemote.AppendText(text);
}
/// <summary>
/// 显示错误日志
/// </summary>
/// <param name="text"></param>
public void LogError(string text)
{
LogAppendDelegate la = new LogAppendDelegate(LogAppend);
richTextBoxRemote.Invoke(la, Color.Red, DateTime.Now.ToString("HH:mm:ss ") + text);
}
/// <summary>
/// 显示警告信息
/// </summary>
/// <param name="text"></param>
public void LogWarning(string text)
{
LogAppendDelegate la = new LogAppendDelegate(LogAppend);
richTextBoxRemote.Invoke(la, Color.Violet, DateTime.Now.ToString("HH:mm:ss ") + text);
}
/// <summary>
/// 显示信息
/// </summary>
/// <param name="text"></param>
public void LogMessage(string text)
{
LogAppendDelegate la = new LogAppendDelegate(LogAppend);
richTextBoxRemote.Invoke(la, Color.Black, DateTime.Now.ToString("HH:mm:ss ") + text);
}
#endregion追问

给点详细的注释好不好?就这样子很难懂好不好。。。

追答

关键代码就一行。 richTextBoxRemote.SelectionColor = color;
,再追加文字

追问

可问题是若在显示其他颜色的字符串后面打字,那个字也是那种颜色。。。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-07-21
            #region 初始全部颜色初始化
            rtb_in.SelectionStart = 0;//初始位置
            rtb_in.SelectionLength = rtb_in.TextLength;//
            rtb_in.SelectionColor = Color.Black;//
            #endregion
            Regex reg = new Regex(@"(?i)字符串1|字符串2");//设定的需要改变颜色的固定字符串
            MatchCollection mc = reg.Matches(rtb_in.Text, 0);//获取匹配的位置和字符串信息
            foreach (Match item in mc)
            {//逐个字符串变更颜色
                rtb_in.SelectionStart = item.Index;
                rtb_in.SelectionLength = item.Value.Length;
                rtb_in.SelectionColor = Color.Blue;
            }
            rtb_in.SelectionStart = rtb_in.TextLength;//回到了文本末尾

rtb_in表示输入的RichTextBox,简单的输入文本后即时判断并且对预先设定的字符串改变颜色,以上执行放于RichTextBox的TextChanged()事件内即可。

相似回答