Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace ConsoleApplication1
- {
- class Program
- {
- 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;
- }
- }
- class MyExternalProcess
- {
- private bool shouldContinue = true;
- public void startProcess()
- {
- while (shouldContinue)
- {
- Console.WriteLine("Hello");
- Thread.Sleep(1000);
- }
- }
- public void kill()
- {
- // do some stuff
- shouldContinue = false;
- Console.WriteLine("Bye bye");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment