c# - 在 C# 中为 RichTextBox 中的所有事件着色的更快方法

标签 c# richtextbox text-coloring

我有一个 RichTextBox,指定的搜索字符串大约出现了 1000 多次。

我使用以下函数为所有事件着色:

public void ColorAll(string s)
{
    rtbxContent.BeginUpdate();

    int start = 0, current = 0;
    RichTextBoxFinds options = RichTextBoxFinds.MatchCase;
    start = rtbxContent.Find(s, start, options);
    while (start >= 0)
    {
        rtbxContent.SelectionStart  = start;
        rtbxContent.SelectionLength = s.Length;
        rtbxContent.SelectionColor     = Color.Red;
        rtbxContent.SelectionBackColor = Color.Yellow;

        current = start + s.Length;
        if (current < rtbxContent.TextLength)
            start = rtbxContent.Find(s, current, options);
        else
            break;
    }

    rtbxContent.EndUpdate();
}

但是我发现它很慢。

但是,如果我对同一文本中出现次数较少的另一个词的所有出现进行着色,我发现它非常快。

所以我猜缓慢的原因是(这两行可能涉及 UI 刷新):

    rtbxContent.SelectionColor     = Color.Red;
    rtbxContent.SelectionBackColor = Color.Yellow;

有没有更快的方法做同样的工作,比如我在内存中着色,然后一次性显示结果?

我表达清楚了吗?

谢谢。

最佳答案

有一个更快的方法。

使用正则表达式查找匹配项然后在富文本框中突出显示

    if (this.tBoxFind.Text.Length > 0)
    {
        try
        {
               this.richTBox.SuspendLayout();
               this.Cursor = Cursors.WaitCursor;

           string s = this.richTBox.Text;
           System.Text.RegularExpressions.MatchCollection mColl = System.Text.RegularExpressions.Regex.Matches(s, this.tBoxFind.Text);

           foreach (System.Text.RegularExpressions.Match g in mColl)
           {
                  this.richTBox.SelectionColor = Color.White;
                  this.richTBox.SelectionBackColor = Color.Blue;

                  this.richTBox.Select(g.Index, g.Length);
           }
   }
   finally
   {
         this.richTBox.ResumeLayout();
         this.Cursor = Cursors.Default;
   }
}

关于c# - 在 C# 中为 RichTextBox 中的所有事件着色的更快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3849261/

相关文章:

c# - 如何从 Web 应用程序中保存富文本并将其显示在富文本框中

c# - 将 richtextbox 保存到文件 C#

c# - 为什么 EF 急切地首先使用 EF 数据库加载所有导航属性?

c# - WPF 中的动态菜单

.NET RichTextBox 制表符

xaml - TextBlock 中的多种颜色

button - JavaFX 按钮文本中的彩色单个字母

objective-c - 当用户键入文本时为文本着色(iOS、Xcode)

c# - 模板字段中的 ASP.NET c# 复选框列表

c# - 将 int 复制到 byte[] 的最简单方法