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

标签 c# process xna launcher child-process

我正在开发游戏启动器应用程序。很像 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 的 Load Content 方法中。

我的问题是如何在 run 进程启动的所有子进程完成后打开窗口?

就像启动器启动游戏一样。

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

提前致谢!

最佳答案

您可以使用 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 事件开始,然后当您了解它是如何工作的时,转向信号量

关于c# - 等待已运行进程的所有子进程完成 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18145721/

相关文章:

silverlight - 性能分析 Windows Phone 7 应用程序 (SL/XNA)

c# - asp.net c# 分配字符串的奇怪问题

c# - Linux Mono + Postsharp + Log4Net = 没有自动异常捕获

winforms - 启动进程 TopMost

python - 为什么我的 Python 程序平均每个进程只有 33% 的 CPU?如何让 Python 使用所有可用的 CPU?

计算执行该程序时c程序中上下文切换的次数

c# - FBX 模型无法在 XNA 4.0 中正确显示

c# - Reactive Extensions - 将项目从一个集合抽取到另一个集合

C# : Fastest way for specific columns in CSV Files

c# - 如何尽快播放声音?