title: Handling COM events from IE
body: <p>I've got a requirement to monitor all instances of IE on a client PC and act on the browser navigating to certain pages and again act on them navigating away from those pages or closing the windows that hosted those pages.</p>
  
  <p>I've written the following code that will list all open windows:</p>
  
  <pre><code>private static void ListWindows()
  {
      SHDocVw.ShellWindows shellWindows = new ShellWindows();
  
      shellWindows.WindowRegistered += new DShellWindowsEvents_WindowRegisteredEventHandler(shellWindows_WindowRegistered);
      foreach (SHDocVw.IWebBrowser2 ie in shellWindows)
      {
          Console.WriteLine("ie.LocationURL: " + ie.LocationURL);
      }
  }
  </code></pre>
  
  <p>Based in part on the <a href="https://stackoverflow.com/questions/6530083/cannot-add-c-windows-system32-shdocvw-dll-to-my-project/8541532#8541532">answer to this question</a>.</p>
  
  <p>But I'd need to poll every second or so and run through that list every time if I were to use that.</p>
  
  <p>I've also found some code that allows me to register for events as follows:</p>
  
  <pre><code>        SHDocVw.InternetExplorer IE = new SHDocVw.InternetExplorer();
  
          IE.BeforeNavigate2 += new DWebBrowserEvents2_BeforeNavigate2EventHandler(IE_BeforeNavigate2);
          IE.OnQuit += new DWebBrowserEvents2_OnQuitEventHandler(IE_OnQuit);
          IE.WindowClosing += new DWebBrowserEvents2_WindowClosingEventHandler(IE_WindowClosing);
  </code></pre>
  
  <p>But that seems to only work on windows that I've opened myself (Either that or I'm doing something wrong). Is there a way to register an event handler for any IE window on a desktop?</p>