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

7

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

7个回答

14

好的,我解决了:

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

我在广阔的网络中搜索了很久,查看了无数的解决方案,但它们都没有起作用。但是这个,终于这个,给了我我想要的东西。谢谢,Marc。 - Leif Wickland
这不起作用!!!需要方法名??请告诉我我错过了什么,我已经在网上搜索了三天 :'( - Pomster
此答案是用VB编写的。 - William Jockusch
另外,还有 System.Windows.Forms.WebBrowser 和 System.Windows.Controls.WebBrowser。如果你正在使用另一个 WebBrowser 类,那么在线查找代码可能会非常困惑。 - William Jockusch
1
我在下面的答案中放置了Marc的VB代码的C#等效代码。它可以工作 :) - kurt

5
为了实现滚动,我们发现ScrollIntoView方法非常有效。例如,要滚动到页面的左上角。
 this.webBrowser.Document.Body.FirstChild.ScrollIntoView(true);

然而,我们并未成功获取滚动位置(也许是因为我们没有花太多时间尝试)。如果您掌控HTML内容,可以考虑使用一些JavaScript将滚动位置复制到隐藏元素中,然后使用DOM读取该值。 ScrollTopScrollLeft仅允许在元素边界和其内容之间提供偏移量。似乎没有办法通过这些值来操作滚动。相反,您必须使用ScrollIntoView

我无法控制HTML内容,所以那对我没用。我知道ScrollIntoView和ScrollTo函数,但是我想访问WebBrowser组件中的滚动条来读取值,而不是滚动。当然,我可以自己在页面中插入一些JavaScript并让它读取值,但我不想使用这个选项。 - Niek H.

3

对于任何感兴趣的人,这是与Marc答案等效的C#代码:

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

2
我可以使用以下代码查询滚动位置。
        if (this.webBrowser.Document != null)
        {
            int scrollPosition = this webBrowser.Document.Body.ScrollTop;                
        }

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;
}

0
你可以检查 documentElement
IHTMLElement2 page = 
(wb.Document.DomDocument as IHTMLDocument3).documentElement as IHTMLElement2;
int pos = page.scrollTop;

0

我发现 Kurt 的答案几乎可以用,但是必须将数组引用更改为以下内容:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接