Scrolling WebBrowser programmatically sometimes doesn’t work

Posted on

Problem :

I’m using the System.Windows.Forms.WebBrowser control and I need to do programmatically 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 (works good) (doesn't work)

It’s can be something about the body code, but I can’t figure out.
I’ve also tried:

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

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

Solution :

This example works around quirks in scroll bar properties that can cause the behavior you are seeing.

You will need to add a COM reference to Microsoft HTML Object Library (mshtml) before this will work.

Assuming you have a WebBrowser named webBrowser1, you can try the following. I use a couple different interfaces because I have found that the values returned for the scroll properties are inconsistent.

            using mshtml;

// ... snip ...

            while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
            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;

 webBrowser1.Document.Window.ScrollTo(new Point(50, 50));

this is an easy way to scroll to every point just input your

Leave a Reply

Your email address will not be published. Required fields are marked *