首页 > 代码库 > [No000090]C#捕获控制台(console)关闭事件及响应cmd快捷键
[No000090]C#捕获控制台(console)关闭事件及响应cmd快捷键
捕获控制台(console)关闭事件:
1.Ctrl+C信号;
2.Ctrl+Break信号;
3.用户系统关闭Console时;
4.用户退出系统时;
5.系统将要关闭时;
using System;using System.Runtime.InteropServices;using System.Threading;using System.Diagnostics;namespace ConsoleApplication2{ public delegate bool ConsoleCtrlDelegate(int dwCtrlType); class Program { [DllImport("kernel32.dll")] private static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate handlerRoutine, bool add); private const int CtrlCEvent = 0;//CTRL_C_EVENT = 0;//一个Ctrl+C的信号被接收,该信号或来自键盘,或来自GenerateConsoleCtrlEvent 函数 private const int CtrlBreakEvent = 1;//CTRL_BREAK_EVENT = 1;//一个Ctrl+Break信号被接收,该信号或来自键盘,或来自GenerateConsoleCtrlEvent 函数 private const int CtrlCloseEvent = 2;//CTRL_CLOSE_EVENT = 2;//当用户系统关闭Console时,系统会发送此信号到此 private const int CtrlLogoffEvent = 5;//CTRL_LOGOFF_EVENT = 5;//当用户退出系统时系统会发送这个信号给所有的Console程序。该信号不能显示是哪个用户退出。 private const int CtrlShutdownEvent = 6;//CTRL_SHUTDOWN_EVENT = 6;//当系统将要关闭时会发送此信号到所有Console程序 [STAThread] static void Main(string[] args) { // TODO: 在此处添加代码以启动应用程序 Program cl = new Program(); } public Program() { if (SetConsoleCtrlHandler(new ConsoleCtrlDelegate(HandlerRoutine), true)) { Console.WriteLine("Set SetConsoleCtrlHandler success!!"); } else { Debug.WriteLine("Set SetConsoleCtrlHandler Error!!"); //AsReportFile.WriteFile("", "test.txt", "who close?"); } Console.ReadLine(); } bool HandlerRoutine(int ctrlType) { Console.WriteLine("Set SetConsoleCtrlHandler success!!"); Console.WriteLine("Set SetConsoleCtrlHandler success!!"); Console.WriteLine("Set SetConsoleCtrlHandler success!!"); Console.WriteLine("Set SetConsoleCtrlHandler success!!"); Console.WriteLine("Set SetConsoleCtrlHandler success!!"); Console.WriteLine("Set SetConsoleCtrlHandler success!!"); Console.WriteLine("Set SetConsoleCtrlHandler success!!"); switch (ctrlType) { case CtrlCEvent: System.Console.WriteLine("Ctrl+C keydown"); break; case CtrlBreakEvent: System.Console.WriteLine("Ctrl+Break keydown"); break; case CtrlCloseEvent: System.Console.WriteLine("window closed"); break; case CtrlLogoffEvent: System.Console.WriteLine("log off or shut down"); break; case CtrlShutdownEvent: System.Console.WriteLine("system shut down"); break; default: System.Console.WriteLine(ctrlType.ToString()); break; } for (int i = 0; i < 10; i++) { Console.WriteLine("i is:{0}", i); Thread.Sleep(1000); } return false; } }}
[No000090]C#捕获控制台(console)关闭事件及响应cmd快捷键
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。