c# - Richtextbox 在新文本前加上颜色

标签 c# winforms richtextbox

我在我的 WinForms 中使用了一个 richtextbox 来显示日志。

使用的语言是 C#。

该软件用于插入银行分行的数据,在新分行开始后我想用新颜色显示文本。

我已经看到链接 Color different parts of a RichTextBox string并成功实现。

我的问题是我想在新行前添加而不是追加。即新行将显示在顶部。

我可以通过将代码更改为 box.Text=DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ": "+ text + box 来做到这一点。文本

但是整个文本的颜色都在变化。

这是追加的过程

            box.SelectionStart = box.TextLength;
        box.SelectionLength = 0;

        box.SelectionColor = color;

        box.AppendText(DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ": " + text);
        box.SelectionColor = box.ForeColor;

这是我所做的:

            box.Text=DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ": " + text + box.text;
        box.SelectionStart = 0;
        box.SelectionLength = text.length;
        box.SelectionColor = color;

但这行不通。

最佳答案

1) 切勿直接更改已格式化的 RichtTextBoxText 属性

2) 要追加,请使用RTB.AppendText 函数

3) 要在任何other 位置p 插入,包括开头使用这个:

rtb.SelectionStart = s;            // set the cursor to the target position
rtb.Selection.Length = 0;          // nothing selected, yet
rtb.SelectedText = yourNewText;    // this inserts the new text 

现在您可以添加您想要的格式:

rtb.SelectionStart = s;            // now we prepare the new formatting..
rtb.SelectionLength = yourNewText.Length;   //.. by selecting the text
rtb.SelectionColor = Color.Blue;   // and/or whatever you want to do..
...

关于c# - Richtextbox 在新文本前加上颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38097850/

相关文章:

c# - LoginUser_Authenticate 和 LoggingIn 事件不会触发

c# - 在 C# 中使用数组填充 Xaml

时间:2019-05-17 标签:c#winform: node expand and collapse in TreeView

c# - 如何在 C# 中将列表值从一个类传递到其他形式?

angularjs - 创建富文本编辑器 AngularJS

c# - 为什么我不能从 RichTextBox 的引用创建 RichTextBox

regex - 为什么我不能更改 RichTextBox 中重复单词的颜色?

c# - 在现有查询中插入 Linq 查询部分

c# - Windows 窗体应用程序数据库

c# - 理解 'Center' 对于 RadialGradientBrushes