C# 在C中获取进程的MainWindowHandle#

C# 在C中获取进程的MainWindowHandle#,c#,process,C#,Process,我用c#启动一个流程,如下所示: Process p= new Process(); p.StartInfo.FileName = "iexplore.exe"; p.StartInfo.Arguments = "about:blank"; p.Start(); 有时我已经有一个Internet Explorer实例在运行(我无法控制),当我尝试获取p的MainWindowHandle时: p.MainWindowHandle 我得到一个例外,说进程已经退出 我正在尝试获取Mai

我用c#启动一个流程,如下所示:

 Process p= new Process();
 p.StartInfo.FileName = "iexplore.exe";  
 p.StartInfo.Arguments = "about:blank";
 p.Start();
有时我已经有一个Internet Explorer实例在运行(我无法控制),当我尝试获取p的MainWindowHandle时:

p.MainWindowHandle
我得到一个例外,说进程已经退出

我正在尝试获取MainwindowHandle,以便将其连接到InternetExplorer对象


在运行多个IE实例的情况下如何实现这一点?

Process.MainWindowHandle只会在进程尚未启动或已关闭时引发异常

所以你必须抓住例外情况是这种情况

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;
}
private void Form1\u加载(对象发送方,事件参数e)
{
过程p=新过程();
p、 StartInfo.FileName=“iexplore.exe”;
p、 StartInfo.Arguments=“关于:空白”;
p、 Start();
流程p2=新流程();
p2.StartInfo.FileName=“iexplore.exe”;
p2.StartInfo.Arguments=“关于:空白”;
p2.Start();
尝试
{
if(FindWindow(“iexplore.exe”,2)==p2.MainWindowHandle)
{
MessageBox.Show(“OK”);
}
}
捕获(例外情况除外)
{
Show(“失败:进程不正常!”);
}    
}
私有IntPtr FindWindow(字符串标题,int索引)
{
列表l=新列表();
进程[]进程;
tempProcesses=Process.GetProcesses();
foreach(tempProcesses中的进程进程)
{
如果(proc.MainWindowTitle==标题)
{
l、 添加(proc);
}
}
如果(l.Count>index)返回l[index].MainWindowHandle;
返回(IntPtr)0;
}

如果我有两个运行iexplore.exe的实例,该进程如何关闭?FindWindow(字符串标题,int-index)提供特定索引处的instace。只需将返回类型更改为Process并返回l[index],而不是l[index]。MainWindowHandle。返回进程上的调用.CloseMainWindow()。@Saobi-p.MainWindowHandle将指向使用p.Start()创建的IE实例,而不是另一个实例。但是,如果在p.Start()之后立即访问p.MainWindowHandle,则该进程实际上可能尚未启动。看看p.WaitForInputIdle。