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