Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RichTextBox Formatting is very slow

I am trying to make a simple WYSIWYG editor. I found pretty difficult to format the rtb. It is supposed to format basic things like bold, italic, coloring(and mixed).

What have I found and tried so far:

private void boldButton_Click(object sender, EventArgs e)
{
  int start = rtb.SelectionStart;
  int length = rtb.SelectionLength;

  for (int i = start, max = start + length; i < max; ++i)
  {
    rtb.Select(i, 1);
    rtb.SelectionFont = new Font(rtb.Font, rtb.SelectionFont.Style | FontStyle.Bold);
  }

  rtb.SelectionStart = start;
  rtb.SelectionLength = length;
  rtb.Focus();
}

rtb = richtextbox.

This works as expected, but is terribly slow. I also found the idea about using and formatting directly the RTF, but the format seems too complicated and very easy to mistake it. I hope it is a better solution.

Thank you.

like image 518
Andrei Damian Avatar asked Dec 03 '25 17:12

Andrei Damian


2 Answers

The performance hit is probably down to the fact you're looping through each character instead of doing everything in one go:

        var start = this.rtb.SelectionStart;
        var length = this.rtb.SelectionLength;

        this.rtb.Select(start, length);
        this.rtb.SelectionFont = new Font(this.rtb.Font, this.rtb.SelectionFont.Style | FontStyle.Bold);
like image 72
BlackBox Avatar answered Dec 06 '25 06:12

BlackBox


I've had the same problem myself. Interestingly, I found out that you can speed up formatting by an order of magnitude if you refrain from referencing to the control's properties when looping through. Instead, put the necessary control properties in separate variables before entering the loop. For instance, instead of continuously referencing e.g. richTextBox1.Length, replace with int len = richTextBox1.Length, and then refer to len inside the loop. Instead of referencing to richTextBox1.Text[index], replace with string text = richTextBox1.Text before the loop, and then instead text[index] inside the loop.

like image 22
Loco Barocco Avatar answered Dec 06 '25 07:12

Loco Barocco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!