控制台 没有退出事件/动作么?
比如窗体程序
退出时,清除一下资源或连接啥的,form_closed()里做动作就可以了
控制台咋整的?
[解决办法]
可以用过注册控制台控制事件来检测控制台是否关闭并进行一些清理工作
class Demo
{
public delegate bool HandlerRoutine(ConsoleControlEventType ctrlType);
public enum ConsoleControlEventType : int
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine handlerRoutine,bool Add);
static bool CtrlProc(ConsoleControlEventType ctrlType)
{
switch (ctrlType)
{
case ConsoleControlEventType.CTRL_C_EVENT:
//ctrl+c
break;
case ConsoleControlEventType.CTRL_CLOSE_EVENT:
//可以做些清理工作
return true;
//....
}
return false;
}
static void Main(string[] args)
{
SetConsoleCtrlHandler(CtrlProc, true);
//
//...其他代码
}
}
case CtrlTypes.CTRL_BREAK_EVENT:
Console.WriteLine("CTRL+BREAK received!");
break;
case CtrlTypes.CTRL_CLOSE_EVENT:
Console.WriteLine("Program being closed!");
break;
case CtrlTypes.CTRL_LOGOFF_EVENT:
Console.WriteLine("User is logging off!");
break;
case CtrlTypes.CTRL_SHUTDOWN_EVENT:
Console.WriteLine("User is logging off!");
break;
}
return true;
}, true))
{
Console.WriteLine("Setup Ok!");
while (true)
{
if ((Console.ReadKey()).KeyChar == 'q')
{
break;
}
}
}
}
}
}