1
votes

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.

2
Please define 'slow', along with where this slowness happens. Does the application suddenly get laggy when you press the bold button? - BlackBox
With 2^14 it took about 2.4212091 seconds. WIth 2^15 -> 4.973971 seconds. It seems pretty slow for me. I was expection < 0.5 seconds. - Andrei Damian
You have to turn off the drawing until you are finished with everything in your loop. See RichTextBox BeginUpdate() EndUpdate() Extension Methods Not Working - LarsTech
Why do you only format one character at a time??? The whole loop is unnecessary! Delete it keeping only the 2nd line in it! - TaW
I was reading somewhere that if the characters has mixed font and styles it won't work to do in one step. But I never tried for myself. Thank you for answers, I'll try tomorrow. - Andrei Damian

2 Answers

1
votes

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

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.