Wait 3 seconds when you click close the console

0

How can I make it wait 3 seconds to close the console?

Thread.Sleep(3000)

I just do not know how to apply to the console. Can you explain?

He would press the X button to close the console and wait for 3 seconds to close

    
asked by anonymous 19.11.2017 / 23:10

1 answer

0

I think this is what you want ...

using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        // http://www.pinvoke.net/default.aspx/kernel32.setconsolectrlhandler
#region pinvoke
        [DllImport("kernel32.dll")]
        static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add);

        // Delegate type to be used as the Handler Routine for SCCH
        delegate Boolean ConsoleCtrlDelegate(CtrlTypes CtrlType);

        // Enumerated type for the control messages sent to the handler routine
        enum CtrlTypes : uint
        {
            CTRL_C_EVENT = 0,
            CTRL_BREAK_EVENT,
            CTRL_CLOSE_EVENT,
            CTRL_LOGOFF_EVENT = 5,
            CTRL_SHUTDOWN_EVENT
        }
#endregion

        static void Main(string[] args)
        {
            var consoleCtrl = new ConsoleCtrlDelegate(ConsoleCtrlCheck);
            GC.KeepAlive(consoleCtrl);

            SetConsoleCtrlHandler(consoleCtrl, true);

            while(true)
            {
                // tarefa longa, mantendo o console aberto ...
            }
        }

        private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
        {
            if (ctrlType == CtrlTypes.CTRL_CLOSE_EVENT)
            {
                Console.WriteLine("3...");
                Thread.Sleep(1000);
                Console.WriteLine("2...");
                Thread.Sleep(1000);
                Console.WriteLine("1...");
                Thread.Sleep(1000);
                Console.WriteLine("Tchau!");
            }

            return true;
        }
    }
}
    
19.11.2017 / 23:48