Selection in RichTextBox is too long

I have a large list of offsets that I need to highlight in my RichTextBox. However, this process takes too much time. 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 this?

UPDATE:

I tried to use this method, but did not isolate anything:

 richTextBox.SelectionBackColor = Color.Yellow; foreach (int offset in offsets) { richTextBox.Select(offset, searchString.Length); } 
+6
source share
3 answers

I was looking for your problem and I found that the RichTextBox gets very slow when you have a lot of lines.
In my opinion, you either buy a third-part control that can be satisfied with its performance, or you may need threads to share the entire task of choice. I think they can speed up the process.
Hope this helps!

+1
source

I had the same problem. In the end, I ignored all the methods they gave you and manipulated the RTF data. Also, the reason your second block of code doesn't work is because RTF applies formatting as it appears, so if you call a function (or property in this case) to change the highlight color, it only applies to to the currently selected block. Any changes made to the selection after this call become invulnerable.

You can play with RGB values, or here is a great source on how to do different things in an RTF control. Paste this function into your code and see how it works. I use it to provide real-time 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; } 
+1
source

It doesn't matter if you set SelectionBackColor outside the loop?

A look at the RichTextBox with Reflector shows that WindowMessage is sent to the control every time the color is set. In the case of a large number of offsets, this can lead to highlighting already selected words again and again, which will lead to the behavior of O (n ^ 2).

0
source

Source: https://habr.com/ru/post/916301/


All Articles