Inconsistent Results with RichTextBox ScrollToCaret

后端 未结 4 788
-上瘾入骨i
-上瘾入骨i 2020-12-20 16:18

I am working with a RichTextBox in C#. It exists on a TabPage. When the TabPage is selected, I aim to populate the RichTextBox, and scroll to the end. I have tried the sligh

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-20 16:44

    I have encountered the same bug (now 7+ years old), of ScrollToCaret() jumping alternatively between the last line and almost the last line. Another solution which avoids using unmanaged code is to call ScrollToCaret() twice.

    RichBox.Select(TheLocationYouWantToScrollTo, 0);
    RichBox.ScrollToCaret();
    RichBox.ScrollToCaret();
    

    This approach can sometimes produce a little screen flicker (not bad, but not super smooth) because it is scrolling to one line and then the other. You might try to solve the slight flicker this way, but it won't work:

    RichBox.SuspendLayout(); // I won't actually suspend this layout
    RichBox.Select(TheLocationYouWantToScrollTo, 0);
    RichBox.ScrollToCaret();
    RichBox.ScrollToCaret();
    RichBox.ResumeLayout();
    

    You can also reduce flicker by making sure the new Location is on a new line:

    RichBox.Select(TheLocationYouWantToScrollTo, 0)
    if (RichBox.Transcription.GetFirstCharIndexOfCurrentLine() != ThePriorCharIndexOfCurrentLine)
    {
       RichBox.ScrollToCaret();
       RichBox.ScrollToCaret(); 
    }
    

    This reduces flicker by only scrolling when we are at a new line.

提交回复
热议问题