Scrolling WebBrowser programmatically sometimes does not work

I am using a control System.Windows.Forms.WebBrowserand I need to perform programmatic scrolling.

For example, I use this code to scroll down:

WebBrowser.Document.Body.ScrollTop += WebBrowser.Height

The problem is that in some sites it works, but in others it doesn’t

http://news.google.com (works good)
http://stackoverflow.com/ (doesn't work)

It might be something about body code, but I can't figure it out.
I also tried:

WebBrowser.Document.Window.ScrollTo(0, 50)

but that way I don’t know the current position.

+5
source share
2 answers

This example works around quirks in the properties of the scroll bar, which can cause the behavior you see.

You will need to add a COM link to the Microsoft HTML Object Library (mshtml) before this works.

, WebBrowser webBrowser1, . , , , , .

            using mshtml;

// ... snip ...

            webBrowser1.Navigate("http://www.stackoverflow.com");
            while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
            {
                Application.DoEvents();
                System.Threading.Thread.Sleep(20);
            }
            Rectangle bounds = webBrowser1.Document.Body.ScrollRectangle;
            IHTMLElement2 body = webBrowser1.Document.Body.DomElement as IHTMLElement2;
            IHTMLElement2 doc = (webBrowser1.Document.DomDocument as IHTMLDocument3).documentElement as IHTMLElement2;
            int scrollHeight = Math.Max(body.scrollHeight, bounds.Height);
            int scrollWidth = Math.Max(body.scrollWidth, bounds.Width);
            scrollHeight = Math.Max(body.scrollHeight, scrollHeight);
            scrollWidth = Math.Max(body.scrollWidth, scrollWidth);
            doc.scrollTop = 500;
+4
 webBrowser1.Document.Window.ScrollTo(new Point(50, 50));

,

+4

All Articles