6

Does anyone know how to react to the ctrl+c event in a console in c# in windows?

this question: Capture console exit C# says how to do it, but I've tried and it only captures the event when the user click the close X in the top of the console window.

Nothing happens when the user types ctrl+c, it doesn't even hit the handler when debugging.

Thanks

Here is my code

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


        }
    }
}
Community
  • 1
  • 1
samwa
  • 323
  • 3
  • 10

2 Answers2

4

That works for me on Windows 7. Closing with x-button
the secret is the variable static 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
    }
Roland
  • 398
  • 2
  • 10
1

You need to wire up the Console.CancelKeyPress event to a handler. Here is a great article on the topic.

awright18
  • 2,255
  • 2
  • 23
  • 22
  • unfortunately that doesn't work for me, I copied and pasted the code directly into a new console app. I noticed this was written in 2006, could it be because I'm using windows 7? – samwa Jan 23 '11 at 20:36
  • That should be correct can you add the code you tried to your question. should just have to add Console.CancelKeyPress += new ConsoleCancelEventHandler(myHandler); to your main method – awright18 Jan 23 '11 at 22:22
  • That link is broken now. – Ben Walker Mar 19 '14 at 16:13
  • Added an msdn link instead. – awright18 Mar 28 '14 at 19:01