如何在.NET中检索webbrowser控件的滚动条位置

时间:2009-08-14 12:54:18

标签: c#

我尝试使用webBrowser1.Document.Body.ScrollTopwebBrowser1.Document.Body.ScrollLeft,但它们不起作用。它们始终返回0,我无法访问webBrowser1.Document.documentElement.ScrollTop.ScrollLeft

7 个答案:

答案 0 :(得分:13)

好的,我解决了它:

Dim htmlDoc As HtmlDocument = wb.Document
Dim scrollTop As Integer = htmlDoc.GetElementsByTagName("HTML")(0).ScrollTop

答案 1 :(得分:5)

为了实际滚动,我们发现ScrollIntoView方法效果很好。例如,要滚动到页面的左上角。

 this.webBrowser.Document.Body.FirstChild.ScrollIntoView(true);

然而,我们没有成功地获得滚动位置(也就是说,我们没有花太多时间尝试)。如果您控制HTML内容,可以考虑使用一些javascript将滚动位置复制到隐藏元素中,然后使用DOM读取该值。

ScrollTopScrollLeft仅允许在元素的边界与其内容之间提供偏移。似乎无法通过这些值操纵滚动。相反,您必须使用ScrollIntoView

答案 2 :(得分:2)

对于任何有兴趣的人,这里的C#代码相当于Marc的答案:

System.Windows.Forms.HtmlDocument htmlDoc = webBrowser.Document;
if (htmlDoc != null)
{
    int scrollTop = htmlDoc.GetElementsByTagName("HTML")[0].ScrollTop;
    int scrollLeft = htmlDoc.GetElementsByTagName("HTML")[0].ScrollLeft;
}

答案 3 :(得分:1)

我能够使用此

查询滚动位置
        if (this.webBrowser.Document != null)
        {
            int scrollPosition = this webBrowser.Document.Body.ScrollTop;                
        }

答案 4 :(得分:0)

您可以查看documentElement

IHTMLElement2 page = 
(wb.Document.DomDocument as IHTMLDocument3).documentElement as IHTMLElement2;
int pos = page.scrollTop;

答案 5 :(得分:0)

接受的答案是VB。对于C#WPF WebBrowser,我必须编写以下内容。不知道我是否真的需要所有这些演员表。如果一个人可以摆脱任何一个演员,那就太棒了。

using mshtml;
int? GetScrollTop(System.Windows.Controls.WebBrowser browser)
{
  object doc = browser.Document;
  HTMLDocument castDoc = doc as HTMLDocument;
  IHTMLElementCollection elements = castDoc?.getElementsByTagName("HTML");
  IEnumerator enumerator = elements?.GetEnumerator();
  enumerator?.MoveNext();
  var first = enumerator?.Current;
  IHTMLElement2 castFirst = first as IHTMLElement2;
  int? top = castFirst?.scrollTop;
  return top;
}

答案 6 :(得分:0)

我发现kurt的答案几乎有效,但必须按如下方式更改数组引用:

var document = (HTMLDocument)Browser.Document;
var scrollTop = (int)document.getElementsByTagName("HTML").item(0).ScrollTop;