【问题标题】:RichTextBox color specific lineRichTextBox 颜色特定行
【发布时间】:2019-02-20 16:44:22
【问题描述】:

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

【问题讨论】:

    标签: c# winforms


    【解决方案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);
      }
    }
    

    【讨论】:

    • 很高兴它帮助了你
    • @gabrielgoller 请将其标记为答案。
    【解决方案2】:

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

    另见:Selectively coloring text in RichTextBox

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多