Guest User

C# - Catching ctrl+c event example

a guest
Nov 3rd, 2013
1,104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.71 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9.  
  10. namespace ConsoleApplication1
  11. {
  12.     class Program
  13.     {
  14.         static ConsoleEventDelegate handler;
  15.         private delegate bool ConsoleEventDelegate(int eventType);
  16.         [DllImport("kernel32.dll", SetLastError = true)]
  17.         private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
  18.  
  19.         private static MyExternalProcess p1;
  20.  
  21.         public static void Main()
  22.         {
  23.             Console.CancelKeyPress += delegate
  24.             {
  25.                 killEveryoneOnExit();
  26.             };
  27.  
  28.             handler = new ConsoleEventDelegate(ConsoleEventCallback);
  29.             SetConsoleCtrlHandler(handler, true);
  30.  
  31.             p1 = new MyExternalProcess();
  32.             p1.startProcess();
  33.         }
  34.  
  35.         public static void killEveryoneOnExit()
  36.         {
  37.             p1.kill();
  38.         }
  39.  
  40.         static bool ConsoleEventCallback(int eventType)
  41.         {
  42.             if (eventType == 2)
  43.             {
  44.                 killEveryoneOnExit();
  45.             }
  46.             return false;
  47.         }
  48.     }
  49.  
  50.     class MyExternalProcess
  51.     {
  52.  
  53.         private bool shouldContinue = true;
  54.  
  55.         public void startProcess()
  56.         {
  57.             while (shouldContinue)
  58.             {
  59.                 Console.WriteLine("Hello");
  60.                 Thread.Sleep(1000);
  61.             }
  62.         }
  63.  
  64.         public void kill()
  65.         {
  66.             // do some stuff
  67.             shouldContinue = false;
  68.             Console.WriteLine("Bye bye");
  69.         }
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment