WPF Application Boilerplate

using System;
using System.Text;
using System.Windows;

public partial class App : Application
{
    [STAThread]
    private static void Main(string[] args)
    {
        try
        {
            App app = new App();
            app.Run();
        }
        catch (Exception ex)
        {
            HandleError(ex);
        }
    }

    private static void HandleError(Exception ex)
    {
        Clipboard.SetText(ex.ToString());
        StringBuilder message = new StringBuilder();
        message.AppendLine("The application has encountered an error and must shut down.");
        message.AppendLine();
        message.AppendLine(string.Format("{0}: {1}", ex.GetType(), ex.Message));
        message.AppendLine();
        message.Append("Full details have been copied to the clipboard.");
        MessageBox.Show(message.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
    }

    public App()
    {
        DispatcherUnhandledException += (sender, e) =>
        {
            HandleError(e.Exception);
            e.Handled = true;
            Shutdown(1);
        };
        InitializeComponent();
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        Window window/* = ... */;
        window.Show();
    }
}

Update: April 5, 2018

For something a little less user-hostile, save the stack trace to a temporary file instead of the clipboard:

private static void HandleError(Exception ex)
{
    string path = Path.GetTempFileName();
    File.WriteAllText(path, ex.ToString());
    StringBuilder message = new StringBuilder();
    message.AppendLine("The application has encountered an error and must shut down.");
    message.AppendLine();
    message.AppendLine(string.Format("{0}: {1}", ex.GetType(), ex.Message));
    message.AppendLine();
    message.AppendLine("Full details have been saved to the following file:");
    message.AppendLine();
    message.Append(path);
    MessageBox.Show(message.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}

Leave a Reply

Your email address will not be published.