滚动web浏览器编程有时不工作 [英] Scrolling WebBrowser programatically sometimes doesn't work

查看:129
本文介绍了滚动web浏览器编程有时不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了 System.Windows.Forms.WebBrowser 控制,我需要做的programaticaly滚动。

I'm using the System.Windows.Forms.WebBrowser control and I need to do programaticaly scrolling.

例如,我用这个code向下滚动:

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)

这可能是一些有关身体code,但我想不通。
我也试着:

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 web浏览器,你可以尝试以下。我用了几个不同的接口,因为我发现,返回滚动属性值不一致。

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;

这篇关于滚动web浏览器编程有时不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆