简体   繁体   中英

Highlighting in a RichTextBox is taking too long

I have a large list of offsets which I need to highlight in my RichTextBox. However this process is taking too long. I am using the following code:

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

Is there a more efficient way to do so?

UPDATE:

Tried using this method but it doesn't highlight anything:

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

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 !

I've had this same problem before. I ended up disregarding all of the methods they give you and manipulated the underlying RTF data. Also, the reason that your second block of code doesnt work is that RTF applies formatting as it goes, so if you call a function (or Property in this case) to change the selection color, it will only apply it for the currently selected block. Any changes made to the selection after that call become irrelavent.

You can play around with the RGB values, or here is a great source on how to do different things within the RTF control. Pop this function in your code and see how well it works. I use it to provide realtime syntax highlighting for SQL code.

    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;
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM