在Win Vista中优雅地关闭控制台应用程序,2008年7月
本文关键字:控制台 应用程序 7月 2008年 Vista Win | 更新日期: 2023-09-27 18:01:09
在Windows Vista,2008中运行时,如何处理控制台应用程序中的关闭/x按钮?
我发现我可以使用SetConsoleControlHandler捕获事件,但Windows会在一秒钟(或几毫秒(后强制终止应用程序。这一秒还不够我的应用程序清理。
如果您分离控制台作为响应,它还会关闭您吗?
http://msdn.microsoft.com/en-us/library/ms683150(v=vs.85(.aspx
您可以了解如何检测要关闭的应用程序:
http://geekswithblogs.net/mrnat/archive/2004/09/23/11594.aspx
namespace Detect_Console_Application_Exit2
{
class Program
{
private static bool isclosing = false;
static void Main(string[] args)
{
SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);
Console.WriteLine("CTRL+C,CTRL+BREAK or suppress the application to exit");
while (!isclosing) ;
}
private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
{
// Put your own handler here
switch (ctrlType)
{
case CtrlTypes.CTRL_C_EVENT:
isclosing = true;
Console.WriteLine("CTRL+C received!");
break;
case CtrlTypes.CTRL_BREAK_EVENT:
isclosing = true;
Console.WriteLine("CTRL+BREAK received!");
break;
case CtrlTypes.CTRL_CLOSE_EVENT:
isclosing = true;
Console.WriteLine("Program being closed!");
break;
case CtrlTypes.CTRL_LOGOFF_EVENT:
case CtrlTypes.CTRL_SHUTDOWN_EVENT:
isclosing = true;
Console.WriteLine("User is logging off!");
break;
}
return true;
}
#region unmanaged
// Declare the SetConsoleCtrlHandler function
// as external and receiving a delegate.
[DllImport("Kernel32")]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
// A delegate type to be used as the handler routine
// for SetConsoleCtrlHandler.
public delegate bool HandlerRoutine(CtrlTypes CtrlType);
// An enumerated type for the control messages
// sent to the handler routine.
public enum CtrlTypes
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT
}
#endregion
}
}
http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/707e9ae1-a53f-4918-8ac4-62a1eddb3c4a/
作为最后手段,您可以使用Console。ReadLine((可阻止应用程序关闭。。。
然后,您可以进行清理并退出应用程序。
Console.ReadLine()
//your clean up code here
//Exit
System.Windows.Forms.Application.Exit(0)
http://geekswithblogs.net/mtreadwell/archive/2004/06/06/6123.aspx