0

I am using SHDocVw to start new InternetExplorer instance and inject some code in every page user navigates to:

var internetExplorer = new InternetExplorer
{
    Visible = true
};
RegisterEvents(internetExplorer);
internetExplorer.Navigate2(url);

RegisterEvents:

private static void RegisterEvents(InternetExplorer internetExplorer)
{
     internetExplorer.NavigateComplete2 += new DWebBrowserEvents2_NavigateComplete2EventHandler(InternetExplorer_NavigateComplete2);
}

The problem is that it's not fired every time. Sometimes it works, sometimes not. This code is run in async method. Now the best part. I've tried with something like this:

private static void RegisterEvents(InternetExplorer internetExplorer)
        {
            Thread t = new Thread(() =>
            {
                internetExplorer.DocumentComplete += InternetExplorer_DocumentComplete;
                while (true)
                {
                }
            });

            t.Start();
            Debug.WriteLine("RegisterEvents");
        }

Somehow it works everytime! But I don't like this infinite loop. What may be wrong with my first approach? Why second one works and how can I make it better?

akeyo20
  • 23
  • 3
  • You may want to consider using [`WebView2`](https://learn.microsoft.com/en-us/microsoft-edge/webview2/) as support for Internet Explorer is just going to become harder and harder to come by... – Heretic Monkey Sep 04 '20 at 13:23
  • User can open new IE instance out of my app and I need to detect all open instances and add this event. So I have to use SHDocVw. – akeyo20 Sep 04 '20 at 13:27
  • The NavigateComplete returns before all the scripts and java code finishes. So I normally test to make sure an object is not null before using the object. In VBA I usually put a DoEvent inside the while loop and wait for IE.ReadyState != 4 – jdweng Sep 04 '20 at 13:35
  • I have tested the above sample code with the IE 11 browser, and it works fine on my side. [See Here](https://imgur.com/a/EOsIzVa) Are you testing the same page every time? Can you check manually whether page loaded completely when it is not firing the event? It may help to narrow down the issue. – Deepak-MSFT Sep 07 '20 at 06:10
  • I think the problem is add event handler is attached in async code but I don't know how to fix it. It seems to work fine on single thread. – akeyo20 Sep 07 '20 at 07:08
  • Can you provide the code that can exactly reproduce the issue? We can try to check and test it and try to provide you the suggestions for it. – Deepak-MSFT Sep 08 '20 at 09:43

0 Answers0