Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

c# - Format text in Rich Text Box

How Can I format text in Rich Text Box like the following

02/11/2010 - 05:15 PM - Adam: Another test notes added on 2nd November

02/11/2010 - 05:14 PM - Z_kas: Test Notes. STAGE CHANGED TO: N Enq - Send Quote

02/11/2010 - 05:12 PM - user32: Another test notes added on 2nd November

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

as stated by others there is a possible duplication with an earlier question. However, please see a code snippet below. You don’t have to get the length of the text you append in order to change its formatting, just set the format before you append. This (i think) gives better performance if you have a lot of text in the textbox.

This will work as long as there are no selections in the textbox by the user, then strange things will happen that I cannot explain. Perhaps someone else can enlighten us? The same problem appears with the solution proposed in Change color of text within a WinForms RichTextBox. I replaced the “:” you had after the user name just to get my code sample to work more easily with the DateTime thing, this can be easily modified in the “Split”.

       private void AddText(string text)
    {
        string[] str = text.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

        if (str.Length == 2)
        {
            richTextBox1.DeselectAll();
            richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);
            richTextBox1.AppendText(Environment.NewLine + str[0] + ";");
            richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Regular);
            richTextBox1.AppendText(str[1]);
        } // Else?? Well, do something else..
    }

And the call:

        private void button1_Click(object sender, EventArgs e)
    {
        AddText(DateTime.Now.ToString() + " - Mike; Did something");

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...