Manu
Manu

Reputation: 4137

Catching ctrl+c event in console application (multi-threaded)

I have a main thread of a Console Application that runs few external processes this way

    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();
      }
    }          

What I need to do is: when the Main thread is interrupted (exit button or ctrl+c), the other processes should be killed. How do I trigger my method killEveryoneOnExit on CTRL+C or Exit (X) button?

Upvotes: 4

Views: 6599

Answers (1)

Jos Vinke
Jos Vinke

Reputation: 2714

Based on your question there are two events you need to catch.

If you put these two together with your example you get something like this:

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;
}

For a working ctrl c (fun intended) paste example: http://pastebin.com/6VV4JKPY

Upvotes: 8

Related Questions