3

我有一个控制台应用程序的主线程,它以这种方式运行很少的外部进程

    private static MyExternalProcess p1;
    private static MyExternalProcess p2;
    private static MyExternalProcess p3;

    public void Main() {
        p1 = new MyExternalProcess();
        p2 = new MyExternalProcess();
        p3 = new MyExternalProcess();

        p1.startProcess();
        p2.startProcess();
        p3.startProcess();
    }

    public static void killEveryoneOnExit() {
        p1.kill();
        p2.kill();
        p3.kill();
    }


    class MyExternalProcess {
      private Process p;
      ...
      public void startProces() {
             // do some stuff
             PlayerProcess = new Process();
             ....
             PlayerProcess.Start();
             // do some stuff
      }

      public void kill() {
             // do some stuff
             p.Kill();
      }
    }          

我需要做的是:当主线程被中断(退出按钮或 ctrl+c)时,其他进程应该被杀死。如何在 CTRL+C 或退出 (X) 按钮上触发我的方法 killEveryoneOnExit?

4

1 回答 1

5

根据您的问题,您需要捕获两个事件。

如果你把这两个和你的例子放在一起,你会得到这样的结果:

static ConsoleEventDelegate handler;
private delegate bool ConsoleEventDelegate(int eventType);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);

private static MyExternalProcess p1;

public static void Main()
{
    Console.CancelKeyPress += delegate
    {
        killEveryoneOnExit();
    };

    handler = new ConsoleEventDelegate(ConsoleEventCallback);
    SetConsoleCtrlHandler(handler, true);

    p1 = new MyExternalProcess();
    p1.startProcess();
}

public static void killEveryoneOnExit()
{
    p1.kill();
}

static bool ConsoleEventCallback(int eventType)
{
    if (eventType == 2)
    {
        killEveryoneOnExit();
    }
    return false;
}

对于工作 ctrl c(有趣的)粘贴示例: http: //pastebin.com/6VV4JKPY

于 2013-11-03T22:55:54.073 回答