You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET Framework 4.7.2的RichTextBox中实现多行文本分色

实现RichTextBox多行文本分色的方法

要给RichTextBox的不同行设置不同颜色,不能直接通过Text属性赋值(这种方式会丢失所有格式),需要利用RichTextBox的选择格式功能,逐段添加文本并指定颜色。

修改后的代码示例

using System.Drawing;

// 记录当前文本长度,用于定位新添加内容的起始位置
int startPos = CompileLogTB.TextLength;

// 第一行:绿色
CompileLogTB.AppendText(Environment.NewLine + "[+]Successfully compiled file!" + Environment.NewLine);
CompileLogTB.Select(startPos, CompileLogTB.TextLength - startPos);
CompileLogTB.SelectionColor = Color.Green;
startPos = CompileLogTB.TextLength;

// 第二行:深蓝色
CompileLogTB.AppendText("[+]Task has been completed." + Environment.NewLine);
CompileLogTB.Select(startPos, CompileLogTB.TextLength - startPos);
CompileLogTB.SelectionColor = Color.DarkBlue;
startPos = CompileLogTB.TextLength;

// 第三行:深绿色
CompileLogTB.AppendText("[+]You may now check the folder" + Environment.NewLine);
CompileLogTB.Select(startPos, CompileLogTB.TextLength - startPos);
CompileLogTB.SelectionColor = Color.DarkGreen;
startPos = CompileLogTB.TextLength;

// 第四行:灰色
CompileLogTB.AppendText("this application is located for the output." + Environment.NewLine);
CompileLogTB.Select(startPos, CompileLogTB.TextLength - startPos);
CompileLogTB.SelectionColor = Color.Gray;
startPos = CompileLogTB.TextLength;

// 第五行:橙色
CompileLogTB.AppendText("Compiled In 34ms!" + Environment.NewLine);
CompileLogTB.Select(startPos, CompileLogTB.TextLength - startPos);
CompileLogTB.SelectionColor = Color.Orange;

关键说明

  1. AppendText方法:用于在已有文本后追加内容,不会破坏原有格式。
  2. Select方法:选中刚添加的文本段,参数为起始索引和选中长度。
  3. SelectionColor属性:为选中的文本设置颜色。
  4. 记得在代码文件顶部引入System.Drawing命名空间,否则Color类无法使用。

内容的提问来源于stack exchange,提问作者Ash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 10:40:00