Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

c# - Inconsistent Results with RichTextBox ScrollToCaret

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...