如何在.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;
关键说明
AppendText方法:用于在已有文本后追加内容,不会破坏原有格式。Select方法:选中刚添加的文本段,参数为起始索引和选中长度。SelectionColor属性:为选中的文本设置颜色。- 记得在代码文件顶部引入
System.Drawing命名空间,否则Color类无法使用。
内容的提问来源于stack exchange,提问作者Ash
相关产品推荐
相关产品推荐

