views:

1943

answers:

3

I'm using the System.Windows.Forms.WebBrowser control and I need to do programaticaly 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'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.

A: 

Are you maybe trying to scroll before the document has been fully loaded?

Thorsten Dittmar
no, the document is fully loaded
DK39
@whoever - thanks for the downvote! I thought it was a legitimate question...
Thorsten Dittmar
i did not downvote but your question should of been a comment not an answer... that's probably why...
Sander Versluys
Ok, I see. (Note to myself: ask questions in comments :-))
Thorsten Dittmar
+2  A: 

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;

...

            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;
John JJ Curtis
Note that if you set doc.scrollTop to a value larger than can be scrolled to, nothing will happen.
John JJ Curtis
This works for me. You can avoid referencing mshtml by using reflection: var dd = browser.Document.DomDocument; var doc = dd.GetType().InvokeMember ("documentElement", BindingFlags.GetProperty, null, dd, null); doc.GetType ().InvokeMember ("scrollTop", BindingFlags.SetProperty, null, doc, new object [] { 500 });
Joe Albahari
A: 

@JohnC

There is a problem with this line : doc.scrollTop = 500;

This should be : body.scrollTop = 500;

harrisunderwork
Good eye, I fixed the answer
John JJ Curtis