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

标签 .net browser webbrowser-control

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

例如,我使用以下代码向下滚动:

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

问题是在某些网站上它可以工作,但在其他网站上却不行

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

这可能与主体代码有关,但我无法弄清楚。
我也尝试过:

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

但是这样我不知道当前位置。

最佳答案

此示例解决了滚动条属性中可能导致您所看到的行为的怪癖。

在此之前,您需要添加对 Microsoft HTML 对象库 (mshtml) 的 COM 引用。

假设您有一个名为 webBrowser1 的 Web 浏览器,您可以尝试以下操作。我使用了几个不同的接口(interface),因为我发现滚动属性返回的值不一致。

            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;

关于.net - 以编程方式滚动 WebBrowser 有时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/975764/

相关文章:

c# - 如何在 WinForms 应用程序中测试 Web 浏览器控件的 Web UI?

c# - 使用 webbrowser 控件 c# 检测网页何时完全加载

c# - 单击带有 webbrowser c# 的链接

c# - 使用 linq C# 将列表转换为嵌套字典

c# - 修复 "Improper Restriction of xml external entity reference"的最佳方法是什么?

c# - 优先订阅调用

cocoa - 接受文件: namesOfPromisedFilesDroppedAtDestination opens Finder window

javascript - document.execCommand 复制命令不起作用或其他解决方案?

c# - 无法向 IPv6 DNS 发送 UDP DNS 请求?

html - Chrome 中的 CSS 错误