我在我的 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) 切勿直接更改已格式化的 RichtTextBox
的 Text
属性
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/