Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# RichTextBox颜色特定行_C#_Winforms - Fatal编程技术网

C# RichTextBox颜色特定行

C# RichTextBox颜色特定行,c#,winforms,C#,Winforms,如何给RichTextBox中以#开头的行上色,就像python中的注释一样。我有这个代码,但它应该只给其中的行上色。我的代码在编写完一个#后为所有内容着色: private void richTextBox1_TextChanged(object sender, EventArgs e) { string text = richTextBox1.Text; if (richTextBox1.Lines.Contains("#") == true) { int firstch

如何给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);
  }
}

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


另请参见:

如果缺少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);
  }
}

很高兴这有帮助you@gabrielgoller请像回答一样标记它。