static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // 处理未捕获的异常
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            // 捕获程序中未处理的异常(UI线程异常)
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            // 捕获程序中未处理的异常(非UI线程异常)
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            Application.Run(new Form1());
        }

        /// <summary>
        /// 捕获程序中未处理的异常(UI线程异常)
        /// </summary>
        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            Exception ex = e.Exception;
            string str = ex.StackTrace;

            //Log4NetHelper.WriteError(typeof(Exception), "UI线程异常;异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message);
            MessageBox.Show("软件致命报错:" + ex.Message, "软件致命异常");
        }

        /// <summary>
        /// 捕获程序中未处理的异常(非UI线程异常)
        /// </summary>
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            string str = ex.StackTrace;
            //Log4NetHelper.WriteError(typeof(Exception), "非UI线程异常;异常位置:" + str.Substring(str.LastIndexOf("\\") + 1, str.Length - str.LastIndexOf("\\") - 1) + ";异常信息:" + ex.Message);
            MessageBox.Show("软件致命报错:" + ex.Message, "软件致命异常");
        }
    }

 

作者:꧁执笔小白꧂