【问题标题】:How to display a message box asking if user really want to exit the cmd window?如何显示一个消息框,询问用户是否真的要退出 cmd 窗口?
【发布时间】:2024-01-23 03:52:01
【问题描述】:

我有一个在 windows cmd 中运行的简单 C# 控制台应用程序。 当用户单击“X”关闭按钮退出程序时,如何使其显示确认消息框? 就像在 javascript 中一样,confirm("Do you really want to exit??")

【问题讨论】:

  • @RyanWilson 是也不是 - 当用户单击关闭窗口按钮时,这无助于他们做任何事情。
  • 我认为这不可能
  • @Archer 我添加了另一部分来解决他们的问题。请查看更新后的评论。
  • @RyanWilson 我自己也在看。看起来 Win32 挂钩可能是唯一有效的方法。

标签: c# windows cmd command


【解决方案1】:

试试这个代码:

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

【讨论】:

  • 请不要只发布代码作为答案,而应包括说明此代码的作用以及它如何解决问题的问题。带有解释的答案通常质量更高,更有可能吸引投票。
最近更新 更多