Andrei Damian
Andrei Damian

Reputation: 414

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.

Upvotes: 3

Views: 2005

Answers (2)

Loco Barocco
Loco Barocco

Reputation: 179

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.

Upvotes: 2

BlackBox
BlackBox

Reputation: 2233

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

Upvotes: 2

Related Questions