title: I don't want to use Thread.Sleep with SHDocVw.ShellWindows
body: <p>I have a program where I have to get a SHDocVw.InternetExplorer instance from a running IE8 process. To get the instance the example code below runs. For some reason it won't work without the Thread.Sleep. </p>
  
  <p>The Browser.HWND throws InvalidCastException for all instances in the m_IEFoundBrowsers if the Thread.Sleep is removed. When using the Thread.Sleep it works for the IE8 windows.</p>
  
  <p>Does anyone know how to do this in a way not using Thread.Sleep? (I don't like to use the sleep function, usually it just pushes the problems into the future...)</p>
  
  <p>Example code:  </p>
  
  <pre><code>InternetExplorer m_IEBrowser = null;  
  ShellWindows m_IEFoundBrowsers = new ShellWindowsClass();  
  Thread.Sleep(10);                           
  foreach (InternetExplorer Browser in m_IEFoundBrowsers)  
  {  
      try  
       {  
           if (Browser.HWND == (int)m_Proc.MainWindowHandle)  
           {  
                m_IEBrowser = Browser;  
                break;  
           }  
        }  
        catch(InvalidCastException ice)  
        {  
              //Do nothing. Browser.HWND could not execute for this item.  
        }  
  }          
  </code></pre>