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??")
Asked
Active
Viewed 187 times
-2

Seong E Kim
- 55
- 1
- 2
- 6
-
1Possible duplicate of [Show message Box in .net console application](https://stackoverflow.com/questions/29326042/show-message-box-in-net-console-application) combined with (https://stackoverflow.com/questions/4646827/on-exit-for-a-console-application) – Ryan Wilson Aug 29 '19 at 13:51
-
@RyanWilson Yes and no - that won't help them do anything when the user clicks the close window button. – Reinstate Monica Cellio Aug 29 '19 at 13:52
-
I don't think that is possible – cnom Aug 29 '19 at 13:55
-
Is it WinForms? Use the FormClosing event – user10728126 Aug 29 '19 at 13:55
-
1@Archer I added the other piece to solving their question. Please see updated comment. – Ryan Wilson Aug 29 '19 at 13:56
-
1@RyanWilson I was looking at that myself. It looks like Win32 hooks may be the only effective way to do this. – Reinstate Monica Cellio Aug 29 '19 at 13:58
-
@Archer I agree. I think that is the only way to capture the exit event of a console window then use the MessageBox link I gave to show the message box as the OP desires. – Ryan Wilson Aug 29 '19 at 13:59
-
How can I hook the close window button? – Seong E Kim Aug 29 '19 at 15:35
-
@SeongEKim Look at the second link in my first comment. – Ryan Wilson Aug 29 '19 at 16:21
1 Answers
-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
-
1Please 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