Microsoft & .NETVisual C#Connecting to Running Instances of Internet Explorer

Connecting to Running Instances of Internet Explorer

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Environment: Internet Explorer 4 (and above)

Connecting to a running instance of the browser from your application has always been problematic. You need to either write a “Browser Helper Object” or something which the browser needs to instantiate. However, all of the methods I’ve personally been able to find are either over complex or buggy. Therefore, I decided to find a simpler (and bug free) way.

After a little research, I came across a shell interface that would do the trick. It turns out that this is how the shell keeps track of all the shell browsers (both Windows Explorer and Internet Explorer instances!).

Not only does the shell keep track of all Explorer instances, it also notifies when a new Explorer instance is created or deleted.

When you enumerate these Explorer instances, you can query whether as to whether the entry supports the IWebBrowser interface. If it does, it could either be a WebBrowser or a ShellBrowser. Once you obtain the IWebBrowser2 interface, you can either use that interface to manipulate (and communicate with) the Explorer instance or you can trap its events using the DWebBrowserEvents.

Before you get started, you’ll need to include the following two lines somewhere in your project:


#import "mshtml.tlb" <span class="codeComment">// Internet Explorer 5</span>

#import "shdocvw.dll"

Now, simply use the following code to connect to a Web browser instance


void CIEEnumWindowsDlg::ConnectToShell() 

{

 CoInitialize(NULL);



 if(m_spSHWinds == 0) 

 {

  <span class="codeComment">//</span>

  <span class="codeComment">// Get reference to ShellWindows interface</span>

  <span class="codeComment">//</span>

  if(m_spSHWinds.CreateInstance(__uuidof(SHDocVw::ShellWindows)) == S_OK) 

  {

   <span class="codeComment">// Event Sink </span>

   <span class="codeComment">//</span>

   LPCONNECTIONPOINTCONTAINER pConnPtCont;



   if ((m_spSHWinds != NULL) &&

   SUCCEEDED(m_spSHWinds->QueryInterface(IID_IConnectionPointContainer,

   (LPVOID*)&pConnPtCont)))

   {

    ASSERT(pConnPtCont != NULL);

    LPCONNECTIONPOINT pConnPt = NULL;

    DWORD dwCookie = 0;



    if (SUCCEEDED(pConnPtCont->FindConnectionPoint(

     __uuidof(SHDocVw::DShellWindowsEvents), &pConnPt)))

    {

     ASSERT(pConnPt != NULL);

     pConnPt->Advise( this->GetIDispatch(FALSE), &dwCookie);

     pConnPt->Release();

    }



    pConnPtCont->Release();

   }

  }

  else 

  {

   AfxMessageBox("Shell Windows interface is not avilable");

  }

 }

}

Downloads

Download source – 15 Kb

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories