SoFunction
Updated on 2025-03-07

The problem solution for multiple calls to events in C#

Regarding the DocumentCompleted event, the explanation given by MSDN is that it is executed after the document is loaded, but DocumentCompleted is called many times in my program. After checking the information, the following situations 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. MSDN's explanation of these two state values ​​is: Complete the control has completed the loading of the new document and all its contents; Interactive control has loaded enough documents to allow limited user interaction, such as clicking the displayed hyperlink. It can be seen from this that the DocumentCompleted event will actually be called once in the Interactive state and Complete state, so we can judge which time we need according to our needs. The solution example code is as follows:

Copy the codeThe code is as follows:

if(!=)
    return;

2. If a page contains multiple frame pages, the DocumentCompleted event may also be triggered when each frame page is loaded (MSDN interprets it as multiple frames in case of multiple frames. Not every frame will trigger this event, but each frame that triggers the DownloadBegin event will trigger the corresponding DocumentComplete event). In this case, the solution example code is as follows:
Copy the codeThe code is as follows:

if(()!=())
    return;

In addition, MSDN has given another solution, see:

3. I didn't encounter the above two situations, but encountered the third situation: the corresponding code was executed in my DocumentCompleted event, and the DocumentCompleted event was triggered again, and the cycle was repeated endlessly. Using(), it still cannot be stopped. ("about:blank") The problem remains the same. At this time, we can only uninstall the DocumentCompleted event, that is, after executing the code you need in the DocumentCompleted event, let’s say another sentence:

Copy the codeThe code is as follows:

-= new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);