Detect scroll on a WebBrowser control

2019-06-25 01:19发布

问题:

I have the following code that, weirdly, works for a couple of seconds and then stops working (my event handler method stops being called):

public partial class Form1 : Form
{
    private void Form1_Load(object sender, EventArgs e)
    {
        webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
        webBrowser1.Navigate("google.com");
    }

    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        if (!webBrowser1.IsBusy && webBrowser1.Url == e.Url && webBrowser1.ReadyState == WebBrowserReadyState.Complete)
        {
            HTMLWindowEvents_Event windowEvents = webBrowser1.Document.Window.DomWindow as HTMLWindowEvents_Event;
            windowEvents.onscroll += new HTMLWindowEvents_onscrollEventHandler(windowEvents_onscroll);
        }
    }

    private void windowEvents_onscroll()
    {
        HtmlDocument htmlDoc = webBrowser1.Document;
        int scrollTop = htmlDoc.GetElementsByTagName("HTML")[0].ScrollTop;
        string text = scrollTop.ToString();
    }
}

回答1:

OK Found a solution:

    protected override void OnDocumentCompleted(WebBrowserDocumentCompletedEventArgs e)
    {
        Follow();
        if (!IsBusy && Url == e.Url && ReadyState == WebBrowserReadyState.Complete)
        {
            Document.Window.AttachEventHandler("onscroll", DocScroll);
        }
    }

If attached that way it works OK (so far...). Don't even need to use mshtml.