2

我正在编写一个小型控制台应用程序(将作为服务运行),它基本上在运行时启动 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");
            }
        }
    }
}
4

4 回答 4

4

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

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

并添加事件处理程序

public void OnApplicationExit(object sender, EventArgs e)
{
    try
    {
        Console.WriteLine("The application is shutting down.");
    }
    catch(NotSupportedException)
    {
    }
}
于 2011-01-17T21:55:53.380 回答
4

啊我的世界 :)

由于您的控制台应用程序最终将成为 Windows 服务,因此请查看ServiceBase类的OnStopOnPowerEventonPauseonShutDown方法。

于 2011-01-17T21:58:51.427 回答
0

您需要将事件处理程序添加到Application.ApplicationExit事件。

于 2011-01-17T21:53:42.493 回答
0

您说它将作为服务运行。

在这种情况下,ServiceBase 类的受保护方法 OnStop() 将被调用。

http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.onstop(v=VS.85).aspx

于 2011-01-17T22:05:11.040 回答