-2

I have a simple C# console application running in windows cmd. How can I make it display a confirm message box when the user clicks the "X" close button to exit the program? Like in javascript, confirm("Do you really want to exit??")

Seong E Kim
  • 55
  • 1
  • 2
  • 6

1 Answers1

-1

Try this code:

[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:
           DialogResult dialogResult = MessageBox.Show("Do you really want to exit??", "Title", MessageBoxButtons.YesNo);
           if (dialogResult == DialogResult.Yes)
               Environment.Exit(0);
           return true;
       default:
       return false;
   }
}

static void Main(string[] args)
{
    _handler += new EventHandler(Handler);
    SetConsoleCtrlHandler(_handler, true);
    Console.ReadLine();
}

Moz
  • 1
  • 1
  • 1
    Please don't post only code as an answer, but include an explanation what this code does and how it addresses the problem of the question. Answers with an explanation are usually of higher quality and are more likely to attract upvotes. – Mark Rotteveel Aug 29 '19 at 17:26