RichTextBox颜色特定行

时间:2019-02-20 16:44:22

标签: c# winforms

如何在RichTextBox中以#开头的行上色,就像python中的注释一样。我有这段代码,但它应该只对其中#号行进行着色。我的代码在写了一个#之后会为所有内容着色:

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);
  }
}

2 个答案:

答案 0 :(得分:1)

您错过了else条件,也对TexBox中的每一行都进行了如下操作

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);
  }
}

答案 1 :(得分:0)

您必须指定richTextBox1.SelectionLength。您必须将其设置为行长。

另请参阅:Selectively coloring text in RichTextBox