Reader Level:
Articles

Access the Same Instance of Internet Explorer Window

By Rob on June 26, 2008
This tip shows how to open an URL inside an Internet Explorer browser window from your C# application. Furthermore it shows how to update that specific window.
  • 0
  • 0
  • 10394

First you need to create a Windows Forms application using Visual Studio and on the Form, add a TextBox and a Button control. Also, double click on the button control to wirte its click event handler.

You also need to import two namespacces by adding "using SHDocVw;" and "using System.Runtime.InteropServices;" to the top of your code.

You will probably need to add the Microsoft Internet Controls reference as well.

WebBrowserApp webBrowser = null;
InternetExplorer explorer = new InternetExplorerClass();
ShellWindows shWin = new ShellWindows();

public Form1()
{
   InitializeComponent();
   webBrowser = (IWebBrowserApp)explorer;
}

private void button1_Click(object sender, EventArgs e)
{
   //open browser to url typed into text box
  IEOpenOnURL(textBox1.Text);
}

public void IEOpenOnURL(string url)
{
  object o = null;
  bool b = false;

  //check if window is already open
  foreach (InternetExplorer ies in shWin)
  {

     if (ies.HWND == webBrowser.HWND)
      b = true;
   }

  try
  {

    if (b)
    {
      webBrowser .Visible = true;
      webBrowser .Navigate(url, ref o, ref o, ref o, ref o);
    }
    else
    {
      //its not open so create new instance
      explorer = new InternetExplorerClass();
      webBrowser = (IWebBrowserApp)explorer;
      webBrowser .Visible = true;
      webBrowser .Navigate(url, ref o, ref o, ref o, ref o);
    }
  }
  catch (Exception)
  { // implement your exception handling here
  }
}

Rob

Rob is a software developer currently working in Nottingham, England.

COMMENT USING

Trending up