【问题标题】:Scrolling WebBrowser programmatically sometimes doesn't work以编程方式滚动 WebBrowser 有时不起作用
【发布时间】:2010-11-01 19:46:44
【问题描述】:

我正在使用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)

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

【问题讨论】:

  • 您是否尝试在文档完全加载之前滚动?
  • 不,文档已完全加载

标签: .net browser webbrowser-control


【解决方案1】:

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

您需要先添加对 Microsoft HTML 对象库 (mshtml) 的 COM 引用,然后才能使用。

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

            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;

【讨论】:

  • 请注意,如果您将 doc.scrollTop 设置为大于可以滚动到的值,则不会发生任何事情。
  • 这对我有用。您可以通过使用反射来避免引用 mshtml: 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 });
【解决方案2】:
 webBrowser1.Document.Window.ScrollTo(new Point(50, 50));

这是滚动到每个点的简单方法,只需输入您的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多