Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 slight variations on solutions for this common question, the main one being along the lines of:

MyRichTextBox.Select(MyRichTextBox.Text.Length, 0);  
MyRichTextBox.ScrollToCaret();  

or:

MyRichTextBox.SelectionStart = MyRichTextBox.Text.Length;  
MyRichTextBox.ScrollToCaret();  

This is producing inconsistent results, albeit in a predictable manner. It will alternate between scrolling to the bottom, and scrolling one line short of the bottom. Respectively illustrated (sorry for the links, new user so I can't post the images):
Successfully scrolled to bottom
Scrolled to one line short of the bottom
I am surprised to find nothing mentioning this behaviour through my searches, and have decided to ask if anyone here has encountered this, and/or has a solution in mind. If it comes down to it, I suppose I can go with something along the lines of itsmatt's answer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
729 views
Welcome To Ask or Share your Answers For Others

1 Answer

I did some further experimentation with ScrollToCaret and it just does not end up in the same position every time. Since my goal is limited to only scrolling all the way to the bottom, it was then a good candidate for sending the WM_VSCROLL message (277, or 0x115) to the control, with wParam of SB_PAGEBOTTOM (7). This consistently scrolls all the way to the very bottom exactly like I needed:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
private const int WM_VSCROLL = 277;
private const int SB_PAGEBOTTOM = 7;

public static void ScrollToBottom(RichTextBox MyRichTextBox)
{
    SendMessage(MyRichTextBox.Handle, WM_VSCROLL, (IntPtr)SB_PAGEBOTTOM, IntPtr.Zero);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...