简体   繁体   中英

How do you paint a specific line in a richTextBox C#?

Given this text in a RichTextBox :

str1
str2
str3

I don't know the length of all of them.
How can I paint the first line with green color and the third with blue? I read a bit of the SelectionColor but I don't want that the line will be marked. There's another way? Or maybe that way (with SelectionColor ) but can you explain me how can I do it?

Try one of the following ways:

  • giving it's value like this:

     richTextBox1.Find("str1"); richTextBox1.SelectionColor = Color.Green; richTextBox1.Find("str3"); richTextBox1.SelectionColor = Color.Blue; 
  • the other way like this:

     richTextBox1.Select(0, 3);//Select text within 0 and 3 richTextBox1.SelectionColor = Color.Green; richTextBox1.Select(9, 12); richTextBox1.SelectionColor = Color.Blue; 

    Edit: To hide the selection add this line to end of your code :

     richTextBox1.Select(0, 0); 

I don't know the length of all of them.

Here's an alternate approach:

    private void button1_Click(object sender, EventArgs e)
    {
        ColorLine(0, Color.Green);
        ColorLine(2, Color.Blue);
    }

    private void ColorLine(int line, Color clr)
    {
        int index = richTextBox1.GetFirstCharIndexFromLine(line);
        int length = richTextBox1.Lines[line].Length;
        richTextBox1.Select(index, length);
        richTextBox1.SelectionColor = clr;
        richTextBox1.Select(0, 0);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM