【问题标题】:removing RichTextBox lines while keeping the colour of remaining lines in C#删除 RichTextBox 行,同时保持 C# 中剩余行的颜色
【发布时间】:2012-09-05 00:18:42
【问题描述】:

考虑一个 RichTextBox,它有 400 行,包含许多不同颜色的单词和行。

是否可以删除此文本框的前 100 行,而保留剩余单词的颜色。目前,我正在使用下面的代码来删除线条,但它无法保持颜色。

if (rtb.Lines.Count() > 400)
     rtb.Lines = rtb.Lines.Skip(100).ToArray();

【问题讨论】:

    标签: c# colors richtextbox line


    【解决方案1】:

    使用 SelectionText 属性。首先选择要删除的行,然后通过将 SelectionText 设置为空字符串来删除它们。像这样:

       richTextBox1.SelectionStart = 0;
       richTextBox1.SelectionLength = richTextBox1.GetFirstCharIndexFromLine(200);
       richTextBox1.SelectedText = "";
    

    这会保留所有其他行的格式。这可能会导致 UI 上出现明显闪烁,您可以通过将 Begin/EndUpdate 方法实现为 shown here 来抑制这种情况。

    【讨论】:

    • 优雅而简单,比解析 RTF 更好。赞一个!
    • 如果richTextBox1.ReadOnly 设置为false,此解决方案有效。如果不是,它什么都不做。
    【解决方案2】:

    如果要保留格式,则不能使用 Lines 属性。 Lines 派生自 TextBoxBase。您需要使用 Rtf 属性并自己解析返回的字符串中的行。如果您只想获取行数然后解析 RTF,那么您可以执行以下操作:

    // NOTE: I am using Length rather than Count() because the array already knows its length
    if (rtb.Lines.Length > 400)
    {
        // Parse the rtf here to remove the unwanted lines and preserve the format
    }
    

    您需要查看RTF specification 才能准确地提取出实际的线条。换行符由标记 \par 指示。难以处理的行是第一行,因为它可能在实际的第一行文本之前包含额外的信息。

    【讨论】:

      【解决方案3】:

      .SelectedText = "" 在我的应用程序中引发 Windows ding

      所以我找到了第二种解决方案,即使用 .Lines 属性

      if (nbLines > maxLines)
      {
          Array.Copy(rtfBox.Lines, 1,
                     rtfBox.Lines, 0, rtfBox.Lines.Length - 1);
      }
      

      【讨论】:

        猜你喜欢
        • 2021-08-30
        • 1970-01-01
        • 1970-01-01
        • 2018-10-17
        • 1970-01-01
        • 1970-01-01
        • 2011-11-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多