Richtextbox prepend new text with color

老子叫甜甜 提交于 2019-12-02 11:37:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!