2011-01-23 15 views
5

¿Alguien sabe cómo reaccionar ante el evento ctrl + c en una consola en C# en Windows?Salida de la consola de captura C# en Windows 7

esta pregunta: Capture console exit C# dice cómo hacerlo, pero lo he intentado y solo captura el evento cuando el usuario hace clic en el cierre X en la parte superior de la ventana de la consola.

No ocurre nada cuando el usuario escribe ctrl + c, ni siquiera golpea el controlador al depurar.

Gracias

Aquí está mi código

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


     } 
    } 
} 
+2

El depurador se interpone en el camino, también busca Ctrl + C. Comience su programa con Ctrl + F5 para probar esto. –

Respuesta

1

Es necesario cablear el evento Console.CancelKeyPress a un controlador. Here es un gran artículo sobre el tema.

+0

lamentablemente eso no funciona, copié y pegué el código directamente en una nueva aplicación de consola. Noté que esto fue escrito en 2006, ¿podría ser porque estoy usando Windows 7? – samwa

+0

http://msdn.microsoft.com/en-us/library/system.console.cancelkeypress.aspx – awright18

+0

Eso debería ser correcto, puede agregar el código que intentó a su pregunta. debería simplemente agregar Console.CancelKeyPress + = new ConsoleCancelEventHandler (myHandler); a su método principal – awright18

4

que me funciona en Windows 7. Cierre con botón de x-
el secreto es la variable estática ConsoleEventDelegate _D

private static void Main(string[] args) 
{ 
    ConsoleEventHooker.Closed += ConsoleEventHooker_Closed; 
} 

static void ConsoleHooker_Closed(object sender, EventArgs e) 
{ 
} 

ConsoleEventHooker.cs

namespace System 
{ 
    internal static class ConsoleEventHooker 
    { 
     private static bool _initedHooker; 
     private static EventHandler _closed; 
     private static EventHandler _shutdown; 
     private static ConsoleEventDelegate _d; 

     public static event EventHandler Closed 
     { 
      add 
      { 
       Init(); 
       _closed += value; 
      } 
      remove { _closed -= value; } 
     } 

     public static event EventHandler Shutdown 
     { 
      add 
      { 
       Init(); 
       _shutdown += value; 
      } 
      remove { _shutdown -= value; } 
     } 

     private static void Init() 
     { 
      if (_initedHooker) return; 
      _initedHooker = true; 
      _d = ConsoleEventCallback; 
      SetConsoleCtrlHandler(_d, true); 
     } 

     private static bool ConsoleEventCallback(CtrlTypes eventType) 
     { 
      if (eventType == CtrlTypes.CTRL_CLOSE_EVENT) 
      { 
       if(_closed != null) _closed(null,new EventArgs()); 
      } 

      if (eventType == CtrlTypes.CTRL_SHUTDOWN_EVENT) 
      { 
       if (_shutdown != null) _shutdown(null, new EventArgs()); 
      } 
      return false; 
     } 

     // A delegate type to be used as the handler routine 
     // for SetConsoleCtrlHandler. 
     delegate bool ConsoleEventDelegate(CtrlTypes ctrlType); 

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

    } 

    // An enumerated type for the control messages 
    // sent to the handler routine. 
    public enum CtrlTypes 
    { 
     CTRL_C_EVENT = 0, 
     CTRL_BREAK_EVENT, 
     CTRL_CLOSE_EVENT, 
     CTRL_LOGOFF_EVENT = 5, 
     CTRL_SHUTDOWN_EVENT 
    } 
Cuestiones relacionadas