在C# NET中如何检测应用程序的关闭?

4
我正在编写一个小型控制台应用程序(将作为服务运行),基本上是在运行时启动Java应用程序,如果Java应用程序关闭,则关闭自身,并在关闭之前关闭Java应用程序。
我认为前两个功能已经正常工作了,但我不知道如何检测.NET应用程序何时关闭,以便我可以在发生这种情况之前关闭Java应用程序。谷歌搜索只返回有关检测Windows关闭的一堆内容。
有人能告诉我如何处理该部分以及其余部分是否正确吗?
namespace MinecraftDaemon
{
    class Program
    {
        public static void LaunchMinecraft(String file, String memoryValue)
        {
            String memParams = "-Xmx" + memoryValue + "M" + " -Xms" + memoryValue + "M ";
            String args = memParams + "-jar " + file + " nogui";
            ProcessStartInfo processInfo = new ProcessStartInfo("java.exe", args);
            processInfo.CreateNoWindow = true;
            processInfo.UseShellExecute = false;

            try
            {
                using (Process minecraftProcess = Process.Start(processInfo))
                {
                    minecraftProcess.WaitForExit();
                }
            }
            catch
            {
                // Log Error
            }
        }

        static void Main(string[] args)
        {
            Arguments CommandLine = new Arguments(args);

            if (CommandLine["file"] != null && CommandLine["memory"] != null)
            {
                // Launch the Application
                LaunchMinecraft(CommandLine["file"], CommandLine["memory"]);
            }
            else
            {
                LaunchMinecraft("minecraft_server.jar", "1024");
            }
        }
    }
}

我可以问一下你为什么要使用那个包装器吗?你是想确保Minecraft服务器始终运行吗? - Bobby
是的。当使用 .bat 文件启动时,我们的游戏面板无法判断应用程序是否正在运行,因此目前无法使用“启动/停止/重启”功能。 - Michael Pfiffer
4个回答

5

您需要在主方法中注册此事件:

Application.ApplicationExit += new EventHandler(AppEvents.OnApplicationExit);

并添加事件处理程序。
public void OnApplicationExit(object sender, EventArgs e)
{
    try
    {
        Console.WriteLine("The application is shutting down.");
    }
    catch(NotSupportedException)
    {
    }
}

4

0

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接