tags:

views:

1405

answers:

2

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?

+1  A: 

Hi,

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;
}
SuperPro
How can the process be closed if I have two instances of iexplore.exe running ??
Saobi
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
A: 

Are you using IE8? If so, then the iexplore.exe that you have invoked will spawn another child process then immediately exits itself. Your Process object will be holding a link to the exited ie.

Refer to this for more info: http://stackoverflow.com/questions/1568093/how-to-obtain-process-of-newly-created-ie8-window

Jack