如何知道RichTextBox垂直滚动条是否达到最大值?

Ele*_*ios 1 .net c# vb.net richtextbox winforms

当使用richtextbox方法“ ScrollToCaret”时,我需要知道滚动条是否达到顶部/底部边缘。

这是因为当垂直滚动条完全滚动到底部时,如果再次使用“ ScrollToCaret”方法,则会在控件中产生怪异的视觉效果,“它会尝试重试向下滚动,但没有其他滚动内容,我可以”无法理解Richtextbox控件的这种怪异逻辑。

我希望你能理解我,请原谅我的英语。

PS:我正在使用默认的richtextbox垂直滚动条。

Kin*_*ing 5

你得应付一点Win32。该win32方法GetScrollInfo是我们所需要的。有了它,我们可以获得最大范围,拇指的当前位置和Page大小(即thumb大小)。所以我们有这个公式:

最大位置=最大范围-拇指大小

现在是适合您的代码:

//Must add using System.Runtime.InteropServices;
//We can define some extension method for this purpose
public static class RichTextBoxExtension {
    [DllImport("user32")]
    private static extern int GetScrollInfo(IntPtr hwnd, int nBar, 
                                            ref SCROLLINFO scrollInfo);

    public struct SCROLLINFO {
      public int cbSize;
      public int fMask;
      public int min;
      public int max;
      public int nPage;
      public int nPos;
      public int nTrackPos;
    }
    public static bool ReachedBottom(this RichTextBox rtb){
       SCROLLINFO scrollInfo = new SCROLLINFO();
       scrollInfo.cbSize = Marshal.SizeOf(scrollInfo);
       //SIF_RANGE = 0x1, SIF_TRACKPOS = 0x10,  SIF_PAGE= 0x2
       scrollInfo.fMask = 0x10 | 0x1 | 0x2;
       GetScrollInfo(rtb.Handle, 1, ref scrollInfo);//nBar = 1 -> VScrollbar
       return scrollInfo.max == scrollInfo.nTrackPos + scrollInfo.nPage;
    }
}
//Usage:
if(!yourRichTextBox.ReachedBottom()){
   yourRichTextBox.ScrollToCaret();
   //...
}
Run Code Online (Sandbox Code Playgroud)