简体   繁体   中英

RichTextBox color specific line

How can I color a line in the RichTextBox which begins with a #, so like a comment in python. I have this code but it should color only the line where the # is in it. My code colors everything after one # is written:

private void richTextBox1_TextChanged(object sender, EventArgs e)
{
  string text = richTextBox1.Text;
  if (richTextBox1.Lines.Contains("#") == true)
  {
    int firstcharindex = richTextBox1.GetFirstCharIndexOfCurrentLine();
    int currentline = richTextBox1.GetLineFromCharIndex(firstcharindex);
    richTextBox1.Select(firstcharindex, 10);
    richTextBox1.SelectionColor = Color.Red;
    richTextBox1.DeselectAll();
    richTextBox1.Select(richTextBox1.Text.Length, 0);
  }
}

You are missing the else condition, also do it for each line within TexBox like below

string text = richTextBox1.Text;
foreach (var line in richTextBox1.Lines)
{
  if (line.Contains("#"))
  {
    int firstcharindex = richTextBox1.GetFirstCharIndexOfCurrentLine();
    int currentline = richTextBox1.GetLineFromCharIndex(firstcharindex);
    richTextBox1.Select(firstcharindex, 10);
    richTextBox1.SelectionColor = Color.Red;
    richTextBox1.DeselectAll();
    richTextBox1.Select(richTextBox1.Text.Length, 0);
  }
  else
  {
    int firstcharindex = richTextBox1.GetFirstCharIndexOfCurrentLine();
    int currentline = richTextBox1.GetLineFromCharIndex(firstcharindex);
    richTextBox1.Select(firstcharindex, 10);
    richTextBox1.SelectionColor = Color.Black;
    richTextBox1.DeselectAll();
    richTextBox1.Select(richTextBox1.Text.Length, 0);
  }
}

You have to specify the richTextBox1.SelectionLength . You have to set this to your line length.

Also see: Selectively coloring text in RichTextBox

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