从富文本框控件获取当前滚动位置?

Lan*_*ens 8 c# scrollbar .net-4.0 richtextbox winforms

我已经在互联网上搜索了很多这样的问题,但是我没有看到实际的答案.

我有一个富文本框控件,里面有很多文本.它在此控件中有一些法律信息.默认情况下,"接受"按钮被禁用.我想在滚动事件中检测到v滚动条的位置是否在底部.如果它位于底部,请启用该按钮.

如何检测当前的v滚动条位置?

谢谢!

编辑 我正在使用WinForms(.Net 4.0)

Lar*_*ech 17

这应该让你接近你想要的.此类继承自RichTextBox并使用一些pinvoking来确定滚动位置.ScrolledToBottom如果用户使用滚动条滚动或使用键盘,它会添加一个被触发的事件.

public class RTFScrolledBottom : RichTextBox {
  public event EventHandler ScrolledToBottom;

  private const int WM_VSCROLL = 0x115;
  private const int WM_MOUSEWHEEL = 0x20A;
  private const int WM_USER = 0x400;
  private const int SB_VERT = 1;
  private const int EM_SETSCROLLPOS = WM_USER + 222;
  private const int EM_GETSCROLLPOS = WM_USER + 221;

  [DllImport("user32.dll")]
  private static extern bool GetScrollRange(IntPtr hWnd, int nBar, out int lpMinPos, out int lpMaxPos);

  [DllImport("user32.dll")]
  private static extern IntPtr SendMessage(IntPtr hWnd, Int32 wMsg, Int32 wParam, ref Point lParam);

  public bool IsAtMaxScroll() {
    int minScroll;
    int maxScroll;
    GetScrollRange(this.Handle, SB_VERT, out minScroll, out maxScroll);
    Point rtfPoint = Point.Empty;
    SendMessage(this.Handle, EM_GETSCROLLPOS, 0, ref rtfPoint);

    return (rtfPoint.Y + this.ClientSize.Height >= maxScroll);
  }

  protected virtual void OnScrolledToBottom(EventArgs e) {
    if (ScrolledToBottom != null)
      ScrolledToBottom(this, e);
  }

  protected override void OnKeyUp(KeyEventArgs e) {
    if (IsAtMaxScroll())
      OnScrolledToBottom(EventArgs.Empty);

    base.OnKeyUp(e);
  }

  protected override void WndProc(ref Message m) {
    if (m.Msg == WM_VSCROLL || m.Msg == WM_MOUSEWHEEL) {
      if (IsAtMaxScroll())
        OnScrolledToBottom(EventArgs.Empty);
    }

    base.WndProc(ref m);
  }

}
Run Code Online (Sandbox Code Playgroud)

这就是如何使用它:

public Form1() {
  InitializeComponent();
  rtfScrolledBottom1.ScrolledToBottom += rtfScrolledBottom1_ScrolledToBottom;
}

private void rtfScrolledBottom1_ScrolledToBottom(object sender, EventArgs e) {
  acceptButton.Enabled = true;
}
Run Code Online (Sandbox Code Playgroud)

根据需要调整.


Roo*_*lie 6

以下是我的一种解决方案,效果很好:

Point P = new Point(rtbDocument.Width, rtbDocument.Height);
int CharIndex = rtbDocument.GetCharIndexFromPosition(P);

if (rtbDocument.TextLength - 1 == CharIndex)
{
   btnAccept.Enabled = true;
}
Run Code Online (Sandbox Code Playgroud)


maj*_*jor 5

问题如何获得 RichTextBox 的滚动位置? 可能会有所帮助,请查看此功能

   richTextBox1.GetPositionFromCharIndex(0);
Run Code Online (Sandbox Code Playgroud)