tags:

views:

116

answers:

1

I've searched through related questions but can't find what I need.

I have a richtextbox control. I need to trigger an event when the vertical scrollbar reaches a certain position (say 90% down to the bottom). I've been playing around with the events for the rich textbox but have yet to find anything.

Any help would be greatly appreciated.

A: 

You can handle VScoll event to detect vertical scrolling and use function

private static double GetRichTextBoxScrolPos(RichTextBox textBox)
{
    if(textBox1.TextLength == 0) return 0;
    var p1 = textBox.GetPositionFromCharIndex(0);
    var p2 = textBox.GetPositionFromCharIndex(textBox.TextLength - 1);

    int scrollPos = -p1.Y;
    int maxScrolPos = p2.Y - p1.Y - textBox.ClientSize.Height;

    if(maxScrolPos <= 0) return 0;

    double d = 100.0 * (double)scrollPos / (double)maxScrolPos;
    if(d < 0) d = 0;
    else if(d > 100) d = 100;

    return d;
}

to determine scroll position. Result is in % (100% = fully scrolled to bottom).

Important note: This function is not absolutely accurate, but you may find result accurate enougth. It can be further improved by measuring bottom line height (using Graphics object for example). 100% reliable way is to aquire VScrollBar handle and query its position using WinAPI, but that will requre much more work.

max
Thanks! I'll try it in a few mins :)
Kizaru
Ok, this seems to work. The only issue the function is called frequently on the event. Is there a way for me to limit the function to one call every 5 seconds? It seems it's called almost infinitely when I reset the textbox.
Kizaru
You can unsubscribe from VScroll event when you are planning to update it and subscribe again after updating. If you still need to limit number of calls on time basis, you can cache function result and call time in 2 variables, and quickly return from function with previous result if it is called within 5s.
max
How would I unsubscribe and subscribe?
Kizaru
`myRichTextBox.VScroll -= MyEventHandler; // unsubscribe``myRichTextBox.VScroll += MyEventHandler; // subscribe`
max
How effective would it be to not use VScroll, but use a timer that every tick (2-4 seconds) calls that function and determines whether to do the rest of the stuff? It's not 100% desired use, but it seems to be best and easiest performance compromise? Doesn't every VScroll event call the eventhandler, which is a lot of work in itself?
Kizaru
If you are really experiencing performance issues with VScroll event and can't eliminate them by subscribing/unsubscribing to/from event, of course you can use timer. As for me I had no performance issues in my test application while scrolling textbox.
max