views:

61

answers:

3

Hi,

I have been looking at the Windows API Code Pack 1.1 and have seen a Error sample and would like to integrate it into my Application, the main idea would be for it to show if any error in the application happens, well not any but some that I choose.

How can I program this?

I am using WPF

Thanks

+1  A: 

You can have an catch block at the top-level of your program that will display the form with relevant error details. Or you can trap unhandled exceptions using the Application.UnhandledException (assuming you are using winforms), Application.ThreadException and AppDomain.UnhandledException.

If you want a message window to show up when any exception occurs, handled or not, then you will either have to explicitly write code in each catch block to show the form, or use something like PostSharp to weave in code that shows the form whenever an exception is thrown.

siride
Would you be able to give an example with WPF? Thanks
Sandeep Bansal
I haven't done WPF, so I found this on Microsoft's website: http://msdn.microsoft.com/en-us/library/ms743714.aspx#Unhandled_Exceptions
siride
A: 

The following will catch all exceptions and display them in a messagebox:

[STAThread]
public static void Main() 
{
  Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
  Application.Run(new Form1());
}

private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) 
{
  // work with exception
  MessageBox.Show(e.Exception.Message);
}

Do note that if you're heavy into threading, you might want to test its behaviour with a thread-heavy application.

More information here.

Rafael Belliard
Hi, Can you show how it would look like in a WPF app since the program.cs isn't in the file structure.
Sandeep Bansal
A: 

In the constructor of your App class add:

   DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);

then add a method to the App class similar to the following:

void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        e.Handled = true;
        if (MessageBox.Show("An unexpected error has occurred.  You should exit this program as soon as possible.\n\n" +
                            "Exit the program now?\n\nError details:\n" + e.Exception.Message,
                            "Unexpected error", MessageBoxButton.YesNo) == MessageBoxResult.Yes)

            Shutdown();
    }
grantnz
Works great thanks a lot!
Sandeep Bansal