1

I start a process in c# like this:

 Process p= new Process();
 p.StartInfo.FileName = "iexplore.exe";  
 p.StartInfo.Arguments = "about:blank";
 p.Start();

Sometimes I already have an instance of Internet Explorer running (something I cannot control), and when I try to grab the MainWindowHandle of p:

p.MainWindowHandle

I get an exception, saying the process has already exited.

I am trying to get the MainwindowHandle so I can attach it to an InternetExplorer object.

How can I accomplish this with multiple instances of IE running?

Saobi
  • 16,121
  • 29
  • 71
  • 81

1 Answers1

2

Process.MainWindowHandle does only raise an exception, if the process has not been started yet or has already been closed.

So you have to catch the exception is this cases.

private void Form1_Load(object sender, EventArgs e)
{

    Process p = new Process();
    p.StartInfo.FileName = "iexplore.exe";
    p.StartInfo.Arguments = "about:blank";
    p.Start();

    Process p2 = new Process();
    p2.StartInfo.FileName = "iexplore.exe";
    p2.StartInfo.Arguments = "about:blank";
    p2.Start();

    try
    {
        if (FindWindow("iexplore.exe", 2) == p2.MainWindowHandle)
        {
            MessageBox.Show("OK");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Failed: Process not OK!");
    }    
}


private IntPtr FindWindow(string title, int index)
{
    List<Process> l = new List<Process>();

    Process[] tempProcesses;
    tempProcesses = Process.GetProcesses();
    foreach (Process proc in tempProcesses)
    {
        if (proc.MainWindowTitle == title)
        {
            l.Add(proc);
        }
    }

    if (l.Count > index) return l[index].MainWindowHandle;
    return (IntPtr)0;
}
Timbo
  • 27,472
  • 11
  • 50
  • 75
SuperPro
  • 454
  • 2
  • 6
  • How can the process be closed if I have two instances of iexplore.exe running ?? – Saobi Jul 16 '09 at 19:36
  • FindWindow(string title, int index) gives you the instace at a specific index. Simply change the return type to Process and return l[index] instead of l[index].MainWindowHandle. The call .CloseMainWindow() on the returned Process... – SuperPro Jul 21 '09 at 10:47
  • @Saobi - p.MainWindowHandle will point to the IE instance created with p.Start(), not another one. However, if p.MainWindowHandle is accessed immediately after p.Start(), the process may actually not have STARTED yet. Look at p.WaitForInputIdle. – Derek Johnson Apr 21 '17 at 21:33