1

I have a System.Windows.Controls.WebBrowser. It has some html that is coming from another document that the user is editing. When the html changes, what I want to do is update the WebBrowser's html, then scroll the WebBrowser back to wherever it was. I am successfully cacheing the scroll offset (see How to retrieve the scrollbar position of the webbrowser control in .NET). But I can't get a callback when the load is complete. Here is what I have tried:

// constructor
public HTMLReferenceEditor()
{
      InitializeComponent();
      WebBrowser browser = this.EditorBrowser;
      browser.LoadCompleted += Browser_LoadCompleted;
      //browser.Loaded += Browser_Loaded; // commented out as it doesn't fire when the html changes . . .
}

private void Browser_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
     CommonDebug.LogLine("LoadCompleted");
     this.ScrollWebBrowser();
}

private void ScrollWebBrowser()
{
      WebBrowser browser = this.EditorBrowser;
      ReferenceHierarchicalViewModel rhvm = this.GetReferenceHierarchichalViewModel();
      int? y = rhvm.LastKnownScrollTop; // this is the cached offset. 
      browser?.ScrollToY(y);
}   

The LoadCompleted callbacks are firing all right. But the scrolling is not happening. I suspect the callbacks are coming too soon. But it is also possible that my scroll method is wrong:

public static void ScrollToY(this WebBrowser browser, int? yQ)
{
    if (yQ.HasValue)
    {
        object doc = browser?.Document;
        HTMLDocument castDoc = doc as HTMLDocument;
        IHTMLWindow2 window = castDoc?.parentWindow;
        int y = yQ.Value;
        window?.scrollTo(0, y);
        CommonDebug.LogLine("scrolling", window, y);
        // above is custom log method; prints out something like "scrolling HTMLWindow2Class3 54", which
        // at least proves that nothing is null.
    }
}

How can I get the browser to scroll? Incidentally, I don't see some of the callback methods others have mentioned, e.g. DocumentCompleted mentioned here does not exist for me. Detect WebBrowser complete page loading. In other words, for some reason I don't understand, my WebBrowser is different from theirs. For me, the methods don't exist.

Community
  • 1
  • 1
William Jockusch
  • 26,513
  • 49
  • 182
  • 323
  • Tried your `ScrollToY` code with a `WebBrowser` pointing to www.stackoverflow.com. It scrolled although to scroll halfway through the page I had to specify `y` as 10000. Strange. As for why you don't have `DocumentCompleted` event: it's because you are using the WPF `WebBrowser` control (https://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser(v=vs.110).aspx) not the Windows Forms one (https://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser(v=vs.110).aspx) – Szabolcs Dézsi Feb 28 '16 at 07:27
  • Good grief, had no idea there were two such classes. How confusing. – William Jockusch Feb 28 '16 at 07:53

0 Answers0