The WebBrowser. DocumentCompleted event in C invokes the problem resolution multiple times

  • 2020-12-13 19:04:30
  • OfStack

As for the DocumentCompleted event, the explanation given by MSDN is that it is executed after the document is loaded, but in my program, DocumentCompleted has been called many times. After 1 check of the data, the following situations may occur.

1. After WebBrowser loads a page, the DocumentCompleted event will be executed twice, but the ReadyState status of these two times is different, namely Intercative and Complete respectively. MSDN interprets these two status values as: Complete has finished loading the new document and all its contents; Interactive this control has loaded enough documents to allow limited user interaction, such as clicking on displayed hyperlinks. It follows that the DocumentCompleted event is actually called once in the Interactive state and once in the Complete state, so we can determine which one is needed based on our needs. The solution example code is as follows:


if(webBrowser1.ReadyState!=WebBrowerReadyState.Complete)
    return;

2. If there are multiple frame pages in a page, then it is possible to trigger the DocumentCompleted event once each frame page is loaded. (MSDN interprets DocumentComplete to be triggered multiple times in the case of multiple frames. Not every framework will fire this event, but every framework that fires the DownloadBegin event will fire the corresponding DocumentComplete event. The solution example code in this case is as follows:

if(e.Url.ToString()!=webBrowser1.Url.ToString())
    return;

In addition, MSDN provides another scheme, as shown in the following details:

3. For the above two cases, I did not meet the third one: I executed the corresponding code in my DocumentCompleted event, which triggered another DocumentCompleted event, and so on and on and on. Using webBrowser1.Stop (), still can't stop. The problem of Nagviate("about:blank") remains the same. At this point, we have to uninstall the DocumentCompleted event. After executing the code in the DocumentCompleted event, we can use the following sentence:


webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);


Related articles: