捕获控制台关闭事件
using BSServer.GameServer;
using log4net;
using System.Runtime.InteropServices;namespace BSServer
{internal class Program{#region 控制台关闭public delegate bool ControlCtrlDelegate(int CtrlType);[DllImport("kernel32.dll")]private static extern bool SetConsoleCtrlHandler(ControlCtrlDelegate HandlerRoutine, bool Add);private static ControlCtrlDelegate cancelHandler = new ControlCtrlDelegate(HandlerRoutine);#endregionstatic bool HandlerRoutine(int eventType){Loger.Info("系统关闭。eventType : " + eventType);return false;}static void Main(string[] args){new Loger("svr");SetConsoleCtrlHandler(cancelHandler, true);Loger.Info("系统启动。");Thread.Sleep(-1);Loger.Info("系统关闭。");}}
}
全局捕获报错
通过UnhandledException 来实现。
using BSServer.GameServer;
using log4net;
using System.Runtime.InteropServices;namespace BSServer
{internal class Program{static void Main(string[] args){new Loger("svr");Loger.Info("系统启动。");AppDomain currentDoamin = default(AppDomain);currentDoamin = AppDomain.CurrentDomain;currentDoamin.UnhandledException += GlobalUnhandledExceptionHandler;Thread.Sleep(-1);Loger.Info("系统关闭。");}private static void GlobalUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e){Exception ex = default(Exception);ex = (Exception)e.ExceptionObject;//ILog log = LogManager.GetLogger(typeof(Program));//log.Error(ex.Message + "\n" + ex.StackTrace);Loger.Error("错误:" + ex.Message + "\n" + ex.StackTrace);}}
}
控制台鼠标点击窗口程序会暂停运行的问题
通过关闭控制台程序的快速编辑功能来实现
using BSServer.GameServer;
using log4net;
using System.Runtime.InteropServices;namespace BSServer
{internal class Program{#region 关闭控制台程序的快速编辑//关闭 cmd 窗口默认为快速编辑(quickedit),解决控制台程序,鼠标点击暂停运行const int STD_INPUT_HANDLE = -10;const uint ENABLE_QUICK_EDIT_MODE = 0x0040;[DllImport("kernel32.dll", SetLastError = true)]internal static extern IntPtr GetStdHandle(int hConsoleHandle);[DllImport("kernel32.dll", SetLastError = true)]internal static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint mode);[DllImport("kernel32.dll", SetLastError = true)]internal static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint mode);public static void DisbleQuickEditMode(){IntPtr hStdin = GetStdHandle(STD_INPUT_HANDLE);uint mode;GetConsoleMode(hStdin, out mode);mode &= ~ENABLE_QUICK_EDIT_MODE;SetConsoleMode(hStdin, mode);}#endregionstatic void Main(string[] args){new Loger("svr");DisbleQuickEditMode();Loger.Info("系统启动。");Thread.Sleep(-1);Loger.Info("系统关闭。");}}
}