以编程方式滚动WebBrowser有时不起作用

以编程方式滚动WebBrowser有时不起作用

问题描述:

我正在使用 System.Windows.Forms.WebBrowser 控件,我需要以编程方式进行滚动。

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

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.

此示例解决滚动条属性中的古怪问题,这些古怪问题可能导致您看到的行为。

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

您将需要添加一个COM之前对Microsoft HTML对象库(mshtml)的引用

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

假设您有一个名为webBrowser1的WebBrowser,则可以尝试以下操作。我使用了两个不同的接口,因为我发现为滚动属性返回的值不一致。

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 ...

            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;