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

前端 未结 7 1809
刺人心
刺人心 2020-12-11 18:44

I tried using webBrowser1.Document.Body.ScrollTop and webBrowser1.Document.Body.ScrollLeft, but they don\'t work. They always return 0 and I can\'t

相关标签:
7条回答
  • 2020-12-11 18:59

    OK, I solved it:

    Dim htmlDoc As HtmlDocument = wb.Document
    Dim scrollTop As Integer = htmlDoc.GetElementsByTagName("HTML")(0).ScrollTop
    
    0 讨论(0)
  • 2020-12-11 18:59

    To actually scroll, we found that the ScrollIntoView method worked nicely. For example, to scroll to the top-left of the page.

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

    However, we were not successful in actually getting the scroll position (that said, we didn't spend long trying). If you are in control of the HTML content, you might consider using some javascript to copy the scroll position into a hidden element and then read that value out using the DOM.

    ScrollTop and ScrollLeft merely allow an offset to be provided between the boundary of an element and its content. There appears to be no way to manipulate the scroll by those values. Instead, you have to use ScrollIntoView.

    0 讨论(0)
  • 2020-12-11 19:01

    Accepted answer is VB. For C# WPF WebBrowser, I had to write the following. No idea if I really need all those casts or not. If one can get rid of any of those casts, that would be terrific.

    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 讨论(0)
  • 2020-12-11 19:06

    You can check documentElement

    IHTMLElement2 page = 
    (wb.Document.DomDocument as IHTMLDocument3).documentElement as IHTMLElement2;
    int pos = page.scrollTop;
    
    0 讨论(0)
  • 2020-12-11 19:08

    I found kurt's answer almost worked but had to change the array reference as follows:

    var document = (HTMLDocument)Browser.Document;
    var scrollTop = (int)document.getElementsByTagName("HTML").item(0).ScrollTop;
    
    0 讨论(0)
  • 2020-12-11 19:21

    I was able to query the scroll position using this

            if (this.webBrowser.Document != null)
            {
                int scrollPosition = this webBrowser.Document.Body.ScrollTop;                
            }
    
    0 讨论(0)
提交回复
热议问题