How to know if RichTextBox vertical Scrollbar reached the max value?

前端 未结 2 667
情书的邮戳
情书的邮戳 2021-01-07 02:30

When using the richtextbox method \"ScrollToCaret\" I need to know if the scrollbar reached the top/bottom margin.

This is because when vertical scrollbar is full sc

2条回答
  •  逝去的感伤
    2021-01-07 02:36

    You have to deal with a little Win32. The win32 method GetScrollInfo is what we need. With that we can get the maximum range, the current position of the thumb and the Page size (which is the thumb size). So we have this formula:

    Max Position = Max Range - Thumb size

    Now it's the code for you:

    //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();
       //...
    }
    

提交回复
热议问题