Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 279
duncanportelli Avatar asked May 21 '12 20:05

duncanportelli


2 Answers

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 !

like image 185
HichemSeeSharp Avatar answered Nov 19 '22 05:11

HichemSeeSharp


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;
    }
like image 25
MrWuf Avatar answered Nov 19 '22 04:11

MrWuf