等待已运行进程的所有子进程完成C# [英] Wait for all child processes of a ran process to finish C#
问题描述
我正在为游戏开发Launcher应用程序。就像XNA中的XBOX仪表板一样。我想在启动程序(游戏)退出时重新打开程序。使用一个简单的游戏,它可以正常工作:
I'm developing a Launcher application for games. Much like XBOX Dashboard in XNA. I want to open back my program when the process which it started(the game) exits. With a simple game this is working:
[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来自:
The Game1.Handle is got from:
Handle = Window.Handle;
在Game1的加载内容方法中。
In the Game1's Load Content method.
我的问题是,在运行过程开始的所有子过程完成后,如何使窗口打开?
My question is how I can make the window open up after all the child process that the ran process has started is finished?
就像启动器启动游戏一样。
Like a launcher launches a game.
我想一些更高级的程序员可能会知道窍门。
I think some more advanced programmer may know the trick.
预先感谢!
推荐答案
您可以使用Process.Exited事件
You could use Process.Exited event
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();
对游戏更合适的方法是使用名为信号灯,但我建议您从Exited事件开始,然后在了解其工作原理后,移至信号灯
More appropriate way for the game is to use named semaphore, but I would suggest you to start with Exited event, and then when you understand how it works, move to semaphore
这篇关于等待已运行进程的所有子进程完成C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!