6

我有大量偏移量,需要在我的 RichTextBox 中突出显示。然而这个过程耗时太长。我正在使用以下代码:

foreach (int offset in offsets)
{
    richTextBox.Select(offset, searchString.Length);
    richTextBox.SelectionBackColor = Color.Yellow;
}

有没有更有效的方法来做到这一点?

更新:

尝试使用此方法,但它没有突出显示任何内容:

richTextBox.SelectionBackColor = Color.Yellow;
foreach (int offset in offsets)
{
    richTextBox.Select(offset, searchString.Length);
}
4

3 回答 3

1

I've googled your issue and I found that RichTextBox is getting very slow when having many lines.
In my opinion, you have either buy a third part control which you can be satisfied by its performance or you may need threads to devide the whole selection task. I think they can accelerate things up.
Hope it helps !

于 2012-05-30T21:47:30.513 回答
1

我以前也遇到过同样的问题。我最终无视了他们给你的所有方法并操纵了底层的 RTF 数据。此外,您的第二个代码块不起作用的原因是 RTF 会应用格式,因此如果您调用函数(或本例中的属性)来更改选择颜色,它只会将其应用于当前选定的块. 在该调用之后对选择所做的任何更改都变得无关紧要。

您可以使用 RGB 值,或者这里是关于如何在 RTF 控件中执行不同操作的一个很好的来源。在你的代码中弹出这个函数,看看它的效果如何。我用它为 SQL 代码提供实时语法高亮。

    public void HighlightText(int offset, int length)
    {
        String sText = richTextBox.Text.Trim();
        sText = sText.Insert(offset + length - 1, @" \highlight0");
        sText = sText.Insert(offset, @" \highlight1");
        String s = @"{\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Courier New;}}
            {\colortbl ;\red255\green255\blue0;}\viewkind4\uc1\pard";
        s += sText;
        s += @"\par}";
        richTextBox.Rtf = s;
    }
于 2012-05-31T17:38:02.750 回答
0

Does it make any difference if you set the SelectionBackColor outside of the loop?

Looking into the RichTextBox with Reflector shows, that a WindowMessage is sent to the control every time when the color is set. In the case of large number of offsets this might lead to highlighting the already highlighted words again and again, leading to O(n^2) behavior.

于 2012-05-29T20:34:50.540 回答