Qualcuno sa come reagire all'evento ctrl + c in una console in C# in windows?Capture exit console C# in windows 7
questa domanda: Capture console exit C# dice come farlo, ma ho provato e cattura solo l'evento quando l'utente fa clic sulla stretta X nella parte superiore della finestra della console.
Non succede nulla quando l'utente digita ctrl + c, non colpisce nemmeno il gestore durante il debug.
Grazie
Ecco il mio codice
namespace EventCloseConsole
{
using System.Runtime.InteropServices;
using System;
class Program
{
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);
private delegate bool EventHandler(CtrlType sig);
static EventHandler _handler;
enum CtrlType
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
private static bool Handler(CtrlType sig)
{
switch (sig)
{
case CtrlType.CTRL_C_EVENT:
case CtrlType.CTRL_LOGOFF_EVENT:
case CtrlType.CTRL_SHUTDOWN_EVENT:
case CtrlType.CTRL_CLOSE_EVENT:
Console.WriteLine("Closing");
System.Threading.Thread.Sleep(500);
return false;
default:
return true;
}
}
static void Main(string[] args)
{
_handler += new EventHandler(Handler);
SetConsoleCtrlHandler(_handler, true);
Console.ReadLine();
}
}
}
Il debugger si mette di mezzo, cerca anche Ctrl + C. Avvia il tuo programma con Ctrl + F5 per testarlo. –