Richtextbox 在新文本前面加上颜色 [英] Richtextbox prepend new text with color
问题描述
我使用富文本框在我的 WinForms 中显示日志.
I have used a richtextbox to display logs in my WinForms.
使用的语言是 C#.
该软件用于插入银行分行的数据,新分行开始后我想用新颜色显示文本.
The software is used for inserting data of Bank Branches and after start of new Branch I want to display a text with new color.
我看到了链接 为 RichTextBox 字符串的不同部分着色 并成功实施.
I have seen the link Color different parts of a RichTextBox string and implemeted it successfully.
我的问题是我想添加新行而不是追加.即新行将显示在顶部.
My problem is I want to prepend the new line instead of append. That is the new line will be displayed on top.
我可以通过将代码更改为 box.Text=DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ":" + text + box 来做到这一点.文字
I am able to do this by changing the code to box.Text=DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ": " + text + box.Text
但是整个文本的颜色正在改变.
But the color is changing for the entire text.
这是用于追加的过程
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
属性>
1) Never directly change the Text
property of an already formatted RichtTextBox
2) 要追加,请使用 RTB.AppendText
函数
2) To append use the RTB.AppendText
function
3) 要插入在任何other位置p
,包括开头使用这个:
3) To insert at any other position p
, including the beginning use this:
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
现在您可以添加所需的格式:
Now you can add the formatting you want:
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..
...
这篇关于Richtextbox 在新文本前面加上颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!