如何在RichTextBox同一行设置不同文本颜色,后续内容换行显示?
解决方案
问题出在你当前的RichTextBoxExtensions.AppendText方法中,只要RichTextBox已有内容,每次调用都会先追加换行符再添加文本,导致两次调用生成两行内容。要实现同一行显示不同颜色文本、后续内容再换行的需求,可以通过以下两种方案修改扩展方法:
方案1:拆分基础追加与换行追加方法
修改扩展类,将"追加文本"和"换行后追加文本"拆分为两个独立方法:
public static class RichTextBoxExtensions { // 基础方法:仅追加文本,不自动换行 public static void AppendText(this RichTextBox box, string text, Color color) { box.SelectionStart = box.TextLength; box.SelectionLength = 0; box.SelectionColor = color; box.AppendText(text); box.SelectionColor = box.ForeColor; } // 换行追加方法:在文本前添加换行(如果已有内容) public static void AppendLineText(this RichTextBox box, string text, Color color) { if (!string.IsNullOrWhiteSpace(box.Text)) { box.AppendText("\r\n"); } box.AppendText(text, color); } }
调用方式调整为:
this.Invoke(new Action(delegate () { // 同一行的不同颜色文本,连续调用基础AppendText richTextBox1.AppendText($"Created: {e.FullPath}", Color.GreenYellow); richTextBox1.AppendText($" On: {DateTime.Now}", Color.Yellow); // 后续需要换行的内容,使用AppendLineText // richTextBox1.AppendLineText("下一条日志内容", Color.Blue); }));
方案2:给原方法添加可选参数控制换行
保留单个方法,新增newLineBefore可选参数,手动控制是否在追加前换行:
public static class RichTextBoxExtensions { public static void AppendText(this RichTextBox box, string text, Color color, bool newLineBefore = false) { box.SelectionStart = box.TextLength; box.SelectionLength = 0; box.SelectionColor = color; // 仅当需要换行且已有内容时,才添加换行符 if (newLineBefore && !string.IsNullOrWhiteSpace(box.Text)) { box.AppendText("\r\n"); } box.AppendText(text); box.SelectionColor = box.ForeColor; } }
调用方式:
this.Invoke(new Action(delegate () { // 第一个文本作为新行开头,传入newLineBefore=true richTextBox1.AppendText($"Created: {e.FullPath}", Color.GreenYellow, true); // 第二个文本同一行,无需换行,使用默认参数 richTextBox1.AppendText($" On: {DateTime.Now}", Color.Yellow); }));
两种方案都能实现同一行内显示不同颜色文本,后续新增内容可通过对应方法或参数控制换行。
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

