捕获控制台退出C# [英] Capture console exit C#

查看:238
本文介绍了捕获控制台退出C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制台应用程序包含相当多的线程。有线程监视某些条件并终止程序,如果它们是真的。



我需要一个事件,当程序关闭时可以触发,以便我可以清理所有其他线程并关闭所有文件手柄和连接。我不知道是否有一个已经内置在.NET框架中,所以我在写我自己之前问。



我想知道是否有一个事件:

  MyConsoleProgram.OnExit + = CleanupBeforeExit; 


解决方案

我不知道我在哪里web,但我发现它现在在我的一个老项目。这将允许您在控制台中执行清理代码,例如。当它突然关闭或由于关机...

  [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:
默认值:
return false;
}
}


static void Main(string [] args)
{
//一些biolerplate对关闭窗口事件
_handler + = new EventHandler(Handler);
SetConsoleCtrlHandler(_handler,true);
...
}

更新 / p>

对于那些不检查注释,似乎这个特定的解决方案 Windows 7 强>。以下主题讲座关于此


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆