首页 > 解决方案 > 发生异常且 C# 程序停止时如何调用函数?

问题描述

在 C# 程序中,当发生异常时,我想做一些动作;也就是说,当发生异常并出现异常窗口时,我想截屏并将异常的图像(以及其他信息,例如运行程序的时间和用户)保存在数据库中。请注意,在发生异常的情况下,程序会停止,直到用户单击按钮(如果用户单击退出按钮,应用程序将结束)。 我故意在这里产生了异常;但在现实世界中,我们不知道异常何时会发生。 可执行程序的图像

标签: c#exception

解决方案


如果要捕获所有未处理的异常,则可以使用应用程序线程异常方法。

program.cs你需要注册线程异常,并添加一个方法来做你的处理。

 static class Program
 {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {

            //Register your thread exception method here
            Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1(args));
        }


        //This method will then be called and you can handle your exception anyway you wish
        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
               //Add your custom handling code here
        }
    }

推荐阅读