捕获控制台退出C# [英] Capture console exit C#
问题描述
我需要一个可以在程序关闭时触发的事件,以便我可以清除所有其他线程并关闭所有文件手柄和连接正确。我不知道是否有一个已经内置到.NET框架中,所以我在写我自己之前问我。
我想知道是否有事件沿着以下行:
MyConsoleProgram.OnExit + = CleanupBeforeExit;
我不知道我在哪里找到网络,但我发现它现在在我的一个旧项目。这将允许您在控制台中执行清除代码,例如当它突然关闭或由于关闭...
[DllImport(Kernel32)]
private static extern bool SetConsoleCtrlHandler(EventHandler handler,bool add);
私人委托bool EventHandler(CtrlType sig);
static EventHandler _handler;
枚举CtrlType
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
private static bool处理程序(CtrlType sig)
{
switch(sig)
{
case CtrlType。 CTRL_C_EVENT:
case CtrlType.CTRL_LOGOFF_EVENT:
case CtrlType.CTRL_SHUTDOWN_EVENT:
case CtrlType.CTRL_CLOSE_EVENT:
default:
return false;
}
}
static void Main(string [] args)
{
//某些biolerplate反应关闭窗口事件
_handler + = new EventHandler(Handler);
SetConsoleCtrlHandler(_handler,true);
...
}
更新 / p>
对于那些不检查评论的人,似乎这个特定的解决方案在 Windows 7 STRONG>。以下主题谈论这个
I have a console application that contains quite a lot of threads. There are threads that monitor certain conditions and terminate the program if they are true. This termination can happen at any time.
I need an event that can be triggered when the program is closing so that I can cleanup all of the other threads and close all file handles and connections properly. I'm not sure if there is one already built into the .NET framework, so I'm asking before I write my own.
I was wondering if there was an event along the lines of:
MyConsoleProgram.OnExit += CleanupBeforeExit;
I am not sure where I found the code on the web, but I found it now in one of my old projects. This will allow you to do cleanup code in your console, e.g. when it is abruptly closed or due to a shutdown...
[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:
default:
return false;
}
}
static void Main(string[] args)
{
// Some biolerplate to react to close window event
_handler += new EventHandler(Handler);
SetConsoleCtrlHandler(_handler, true);
...
}
Update
For those not checking the comments it seems that this particular solution does not work well (or at all) on Windows 7. The following thread talks about this
这篇关于捕获控制台退出C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!