2

My file is 450 503 letters text. I have to change every letter (eg. 'b' - user choice) on another and mark it by set red color. When I do it in that way:

 for(int i=0; i<lenght; ++i) {
    this.rtb.Select(i, 1);
    this.rtb.SelectionColor = Color.Red;
    this.rtb.SelectedText = this.rtb.SelectedText;
    this.rtb.DeselectAll();
 }

It's too slooow - actually it never finished... (17min awaiting). I have no idea how to speed it up.

patseb
  • 651
  • 1
  • 8
  • 20
  • don't remember now exactly but isn't there a pair of methods like rtb.BeginUpdate and End or ResumeUpdate ? – Davide Piras Mar 15 '11 at 20:56
  • What's the point of `this.rtb.SelectedText = this.rtb.SelectedText`? – David Heffernan Mar 15 '11 at 20:57
  • A Windows programmer would just fire [`EM_FINDTEXT`](http://msdn.microsoft.com/en-us/library/bb788009(v=VS.85).aspx) messages at the rich edit window and follow each hit with [`EM_SETCHARFORMAT`](http://msdn.microsoft.com/en-us/library/bb774230(v=VS.85).aspx) messages. No doubt there is a .net equivalent. It would be done in seconds. – David Heffernan Mar 15 '11 at 21:00
  • 1
    Suspend/ResumeLayout has an enduring mystique in winforms answers. The real answer is here: http://stackoverflow.com/questions/3282384/richtextbox-syntax-highlighting-in-real-time-disabling-the-repaint/3282911#3282911 – Hans Passant Mar 15 '11 at 21:05

2 Answers2

0

It's because you are forcing it to to redraw everytime it happens.

Wrap this in a SuspendLayout and ResumeLayout

msarchet
  • 15,104
  • 2
  • 43
  • 66
0

Try calling rtb.SuspendLayout(); before running your logic and rtb.ResumeLayout(); afterwards. Like this:

rtb.SuspendLayout();

for(int i=0; i<lenght; ++i) {
    this.rtb.Select(i, 1);
    this.rtb.SelectionColor = Color.Red;
    // you shouldn't need these lines:
    // this.rtb.SelectedText = this.rtb.SelectedText;
    // this.rtb.DeselectAll();
 }

rtb.ResumeLayout();

Optimization aside you do at some point have to check whether the selected letter is the one you want. The current loop will attempt to color every single letter red.

Paul Sasik
  • 79,492
  • 20
  • 149
  • 189