Saobi
Saobi

Reputation: 17041

Getting MainWindowHandle of a process in C#

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?

Upvotes: 1

Views: 11497

Answers (1)

SuperPro
SuperPro

Reputation: 464

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;
}

Upvotes: 2

Related Questions