Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the scrollbar position of the webbrowser control in .NET

Tags:

c#

I tried using webBrowser1.Document.Body.ScrollTop and webBrowser1.Document.Body.ScrollLeft, but they don't work. They always return 0 and I can't access webBrowser1.Document.documentElement.ScrollTop and .ScrollLeft.

like image 959
Niek H. Avatar asked Aug 14 '09 12:08

Niek H.


4 Answers

OK, I solved it:

Dim htmlDoc As HtmlDocument = wb.Document
Dim scrollTop As Integer = htmlDoc.GetElementsByTagName("HTML")(0).ScrollTop
like image 131
Marc Avatar answered Oct 06 '22 02:10

Marc


To actually scroll, we found that the ScrollIntoView method worked nicely. For example, to scroll to the top-left of the page.

 this.webBrowser.Document.Body.FirstChild.ScrollIntoView(true);

However, we were not successful in actually getting the scroll position (that said, we didn't spend long trying). If you are in control of the HTML content, you might consider using some javascript to copy the scroll position into a hidden element and then read that value out using the DOM.

ScrollTop and ScrollLeft merely allow an offset to be provided between the boundary of an element and its content. There appears to be no way to manipulate the scroll by those values. Instead, you have to use ScrollIntoView.

like image 42
Jeff Yates Avatar answered Oct 06 '22 01:10

Jeff Yates


For anyone interested, here's the C# code equivalent to Marc's answer:

System.Windows.Forms.HtmlDocument htmlDoc = webBrowser.Document;
if (htmlDoc != null)
{
    int scrollTop = htmlDoc.GetElementsByTagName("HTML")[0].ScrollTop;
    int scrollLeft = htmlDoc.GetElementsByTagName("HTML")[0].ScrollLeft;
}
like image 37
kurt Avatar answered Oct 06 '22 01:10

kurt


I was able to query the scroll position using this

        if (this.webBrowser.Document != null)
        {
            int scrollPosition = this webBrowser.Document.Body.ScrollTop;                
        }
like image 29
thowa Avatar answered Oct 06 '22 03:10

thowa