Please try the following code. I think you can find the reason, or at least stops crashing.
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
namespace Test_UnhandledException
{
static class Program
{
[STAThread]
static void Main()
{
Application.ThreadException += Application_ThreadException;
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
AddLog((Exception)e.ExceptionObject);
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
AddLog(e.Exception);
}
static void AddLog(Exception exception)
{
try
{
using (StreamWriter sw = new StreamWriter(@"d:\tmp\app.log", true))
{
sw.WriteLine(exception.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}