[英]How to display a message box asking if user really want to exit the cmd window?
我有一個在 Windows cmd 中運行的簡單 C# 控制台應用程序。 當用戶單擊“X”關閉按鈕退出程序時,如何使其顯示確認消息框? 就像在 javascript 中一樣, confirm("Do you really want to exit??")
試試這個代碼:
[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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.