2012-04-19 102 views
4

我已經在網上搜索了很多,看到過很多這樣的問題,但我還沒有看到實際的答案。從富文本框控件獲取當前滾動位置?

我有一個豐富的文本框控件,裏面有很多文本。它在這個控制中有一些合法的信息。默認情況下,「接受」按鈕被禁用。我想檢測滾動事件,如果v-滾動條的位置在底部。如果它位於底部,請啓用該按鈕。

我該如何檢測當前的v-滾動條位置?

謝謝!

編輯 我使用的WinForms(.NET 4.0)

+0

的WinForms或WPF? – 2012-04-19 22:33:46

+0

WinForms,使用.net 4.0 – 2012-04-19 22:38:34

+2

這最好放在標籤中。 – 2012-04-19 22:40:49

回答

12

這應該讓你接近你在找什麼。該類繼承自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); 
    } 

} 

這是那麼它如何能習慣:

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

private void rtfScrolledBottom1_ScrolledToBottom(object sender, EventArgs e) { 
    acceptButton.Enabled = true; 
} 

扭捏是必要的。

+0

非常感謝! – 2012-04-20 03:12:41

+0

請注意,當用戶握住滾動條並移動滾動條時,滾動位置不會更新。只有在鼠標按鈕被釋放後。 – 2013-07-26 01:59:08

+0

您能解釋一下爲什麼我們需要將'this.ClientSize.Height'添加到滾動位置?爲什麼滾動位置不等於'maxScroll',即使滾動位於底部? – 2013-09-03 05:45:34

2

下面的作品非常好我的解決方案之一:

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

if (rtbDocument.TextLength - 1 == CharIndex) 
{ 
    btnAccept.Enabled = true; 
}