问题
I have used a richtextbox to display logs in my WinForms.
Language used is 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.
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.
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.
This is the procedure used for append
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;
This is what I have done:
box.Text=DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss") + ": " + text + box.text;
box.SelectionStart = 0;
box.SelectionLength = text.length;
box.SelectionColor = color;
But this is not working.
回答1:
1) Never directly change the Text
property of an already formatted RichtTextBox
2) To append use the RTB.AppendText
function
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..
...
来源:https://stackoverflow.com/questions/38097850/richtextbox-prepend-new-text-with-color