Reputation: 357
Is there any way to make a program stop and exit the program when it crashes? I am using C# to develop the program and machines it is run on are 32 bit Windows 7 Professional machines.
So, for example, when my X.exe crashes, a little pop-up window with 2 options come up: 1 - Look for solutions online. 2 - Stop X.exe
I want the second option to be automatically selected and my program is stopped. I have another program that monitors X.exe so when X.exe is stopped, it will start a new instance of X.exe.
Upvotes: 0
Views: 2290
Reputation: 5120
This code should guide you the way:
public static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// catch app errors
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
try
{
Application.Run(new Form());
}
catch (Exception exc)
{
// show popupform
PopupForm popup = new PopupForm();
if(popup.ShowDialog() == DialogResult.OK)
{
Application.Restart();
}
else
{
Application.Exit();
}
}
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
// show popupform
PopupForm popup = new PopupForm();
if(popup.ShowDialog() == DialogResult.OK)
{
Application.Restart();
}
else
{
Application.Exit();
}
}
Lg warappa
Upvotes: 2
Reputation: 11760
You can add a global exception handler for unhandled exceptions. This handler is always called when your program did not handle an exception during runtime which will cause the programm to crash:
In Wpf-Applications you can add the handler like this:
App.Current.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler( Current_DispatcherUnhandledException );
The same for WinForms:
System.Windows.Forms.Application.ThreadException += new ThreadExceptionEventHandler( OnThreadException );
And for console applications:
System.AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( OnUnhandledException );
Upvotes: 4