Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何显示询问用户是否确实要退出cmd窗口的消息框?_C#_Windows_Cmd_Command - Fatal编程技术网

C# 如何显示询问用户是否确实要退出cmd窗口的消息框?

C# 如何显示询问用户是否确实要退出cmd窗口的消息框?,c#,windows,cmd,command,C#,Windows,Cmd,Command,我有一个简单的C#控制台应用程序运行在windows cmd中。 当用户单击“X”关闭按钮退出程序时,如何使其显示确认消息框? 与javascript一样,确认(“您真的想退出吗?”)尝试以下代码: [DllImport("Kernel32")] private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add); private delegate bool EventHandler(CtrlType

我有一个简单的C#控制台应用程序运行在windows cmd中。 当用户单击“X”关闭按钮退出程序时,如何使其显示确认消息框? 与javascript一样,
确认(“您真的想退出吗?”)

尝试以下代码:

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


可能与()@RyanWilson相结合的副本是和否-当用户单击关闭窗口按钮时,这不会帮助他们做任何事情。我不认为这是正确的possible@Archer我在解决他们的问题时加入了另一部分。请看最新的评论。@RyanWilson我自己也在看。看起来Win32钩子可能是唯一有效的解决方法。请不要只发布代码作为答案,而是说明此代码的作用以及它如何解决问题。带有解释的答案通常质量更高,更容易吸引选票。