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

Inf*_*tus 5 .net browser webbrowser-control

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

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

WebBrowser.Document.Body.ScrollTop += WebBrowser.Height
Run Code Online (Sandbox Code Playgroud)

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

http://news.google.com (works good)
http://stackoverflow.com/ (doesn't work)
Run Code Online (Sandbox Code Playgroud)

这可能与身体代码有关,但我无法弄明白.
我也尝试过:

WebBrowser.Document.Window.ScrollTo(0, 50)
Run Code Online (Sandbox Code Playgroud)

但这种方式我不知道目前的位置.

jjx*_*tra 5

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

在此之前,您需要添加对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;
Run Code Online (Sandbox Code Playgroud)

  • 这对我有用。您可以通过使用反射来避免引用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,新对象[] {500}); (2认同)