等待运行进程的所有子进程完成C#

时间:2013-08-09 11:30:31

标签: c# process xna launcher child-process

我正在为游戏开发一个Launcher应用程序。很像XNA中的XBOX仪表板。我想在它启动的过程(游戏)退出时打开我的程序。通过一个简单的游戏,这是有效的:

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImportAttribute("User32.DLL")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_SHOW = 5;
private const int SW_MINIMIZE = 6;
private const int SW_RESTORE = 9;

public void Run(file)
{
    ProcessStartInfo startInfo = new ProcessStartInfo(file);
    Environment.CurrentDirectory = Path.GetDirectoryName(file);
    startInfo.Verb = "runas";
    var process = Process.Start(startInfo);
    process.WaitForExit();
    ShowWindow(Game1.Handle, SW_RESTORE);
    SetForegroundWindow(Game1.Handle);
}

Game1.Handle来自:

Handle = Window.Handle;

在Game1的加载内容方法中。

我的问题是如何在完成运行过程的所有子进程完成后打开窗口?

就像发射器发射游戏一样。

我认为一些更高级的程序员可能知道这个伎俩。

提前致谢!

1 个答案:

答案 0 :(得分:2)

您可以使用Process.Exited事件

 int counter == 0;
     .....

     //start process, assume this code will be called several times
     counter++;
     var process = new Process ();
     process.StartInfo = new ProcessStartInfo(file);

     //Here are 2 lines that you need
     process.EnableRaisingEvents = true;
     //Just used LINQ for short, usually would use method as event handler
     process.Exited += (s, a) => 
    { 
      counter--;
      if (counter == 0)//All processed has exited
         {
         ShowWindow(Game1.Handle, SW_RESTORE);
        SetForegroundWindow(Game1.Handle);
         }
    }
    process.Start();

更合适的游戏方式是使用名为semaphore,但我建议您先从Exited事件开始,然后当您了解它的工作方式时,请转到信号量