簡體   English   中英

如何在.NET中檢索webbrowser控件的滾動條位置

[英]How to retrieve the scrollbar position of the webbrowser control in .NET

我嘗試使用webBrowser1.Document.Body.ScrollTopwebBrowser1.Document.Body.ScrollLeft ,但它們不起作用。 它們總是返回0,我無法訪問webBrowser1.Document.documentElement.ScrollTop.ScrollLeft

好的,我解決了它:

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

為了實際滾動,我們發現ScrollIntoView方法運行良好。 例如,滾動到頁面的左上角。

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

但是,我們沒有成功地獲得滾動位置(也就是說,我們沒有花太多時間嘗試)。 如果您控制HTML內容,可以考慮使用一些javascript將滾動位置復制到隱藏元素中,然后使用DOM讀取該值。

ScrollTopScrollLeft僅允許在元素的邊界與其內容之間提供偏移。 似乎無法通過這些值操縱滾動。 相反,您必須使用ScrollIntoView

對於任何感興趣的人,這里的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;
}

我能夠使用此查詢滾動位置

        if (this.webBrowser.Document != null)
        {
            int scrollPosition = this webBrowser.Document.Body.ScrollTop;                
        }

您可以檢查documentElement

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

接受的答案是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;
}

我發現kurt的答案幾乎可以工作,但必須更改數組引用,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM