How to use WebBrowser control DocumentCompleted event in C#?

前端 未结 5 1412
野性不改
野性不改 2020-11-27 16:14

Before starting writing this question, i was trying to solve following

// 1. navigate to page
// 2. wait until page is downloaded
// 3. read and write some d         


        
5条回答
  •  感动是毒
    2020-11-27 16:46

    Unlike Thorsten I didn't have to use ShDocVw, but what did make the difference for me was adding the loop checking ReadyState and using Application.DoEvents() while not ready. Here is my code:

            this.webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
            foreach (var item in this.urlList) // This is a Dictionary
            {
                this.webBrowser.Navigate(item.Value);
                while (this.webBrowser1.ReadyState != WebBrowserReadyState.Complete)
                {
                    Application.DoEvents();
                }
            }
    

    And I used Yuki's solution for checking the results of WebBrowser_DocumentCompleted, though with the last if/else swapped per user's comment:

         private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            string url = e.Url.ToString();
            var browser = (WebBrowser)sender;
    
            if (!(url.StartsWith("http://") || url.StartsWith("https://")))     
            {             
                // in AJAX     
            }
            if (e.Url.AbsolutePath != this.webBrowser.Url.AbsolutePath)     
            {
                // IFRAME           
            }     
            else     
            {             
                // REAL DOCUMENT COMPLETE
                // Put my code here
            }
        }
    

    Worked like a charm :)

提交回复
热议问题