WPF forms crashed - c#

Is there any way to catch the crashed form and reopen it again.
public static void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
}

Setting e.Handler to true should prevent the app from shutting down. You will then have to write some code to bring the window up again. There is no "reopen the crashed form" switch I am afraid. There is not even any notion of a "crashed form" as far as the event handler is concerned.
Please also note that keeping an application running like this will leave it in an undefined state. What you really should do is to catch the exception where it occurs and then use the Dispatcher_UnhandledException event handler as a last resort for logging any unhandled exception, perhaps displaying a user friendly message and finally shutting the application down.

Related

How add something to do when own ErrorHandler event happens?

It was firs time I have used delegate and event. I made an error handler event for Memory Game program. The program has a "lot" of SQL operation. The event functioning wery well. I subscribe a MessageBox "caller void" to print errormessages out in the Main Form. (It was a surprise for me that I had to subscribe this printout void only in the Main and every Form errors are printed out by this little void.)
I have problem with error handling. When I handled the problems with Exceptions I could handle everything to the very end (if Exception not null do....).
Delegate and event is very usefull but I dont know how close the actual form or simply make something to do when an error happens.
I have tried to implement this.close() after MessageBox printed out the message but it closes the whole program.
private void MessageBoxPopUp(string errorMessageForMessageBox)
{
MessageBox.Show(errorMessageForMessageBox);
this.Close();
}
I would like to close the form parented by the main form or I want the program just do nothing. Now The messageBox ("Game saved succeddfully.") pops up after an error message because it is written under the void calling the errorMessage event. With Exception and braces I could separate the different derivations.
Thank you for help,

Unable to show a window from AppDomain.CurrentDomain.UnhandledException that catches an exception in a foreground thread - WPF

I was reading C# in a nutshell (Threading chapter) and was trying to catch a divide by zero exception that I throw in a new thread from a button event handler. The AppDomain.CurrentDomain.UnhandledException fires as expected. The event handling methods simply show a window called "ErrorWindow". When I step into the constructor of the window, the debugger throw the exception back and the window doesn't show.
Here's what I have:
Target Framework: 4.5.2
Target Platform: X64
The application is a WPF windows application and contains two windows:
MainWindow: Has a button that executes the code snippet below.
ErrorWindow: Just a blank window to show in the AppDomain.CurrentDomain.UnhandledException event handler
Code snippet:
var thread = new Thread(() =>
{
int result = 100 / int.Parse("0");
});
thread.Start();
I'm attaching the AppDomain.CurrentDomain.UnhandledException event handler in a StartUp event handler in App.xaml.cs. The event handler simply create a instance of the ErrorWindow and attemtps to show it.
If someone is able to recreate this behavior and explain why, that'd be great. I'll share my VS project if needed.
PS: This only happens when I create a thread. If my DivideByZeroException gets thrown from the main UI thread, then the window shows as expected.
PS: Marshalling the showing of the window to the UI thread doesn't work and I don't expect it to.
Thanks!
IMHO the AppDomain.UnhandledException Event is not meant to show windows or error dialogs. As reported in the Remarks section:
This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application. If sufficient information about the state of the application is available, other actions may be undertaken — such as saving program data for later recovery. Caution is advised, because program data can become corrupted when exceptions are not handled.
Instead, if you want to trap an exception and handle it, you can use the Application.DispatcherUnhandledException Event. In this case you can keep you application alive, just by setting the Handled property to true:
Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
e.Handled = true;
/* Show your error window */
}
But pay attention, because:
If an exception is not handled on either a background user interface (UI) thread (a thread with its own Dispatcher) or a background worker thread (a thread without a Dispatcher), the exception is not forwarded to the main UI thread. Consequently, DispatcherUnhandledException is not raised.
I hope it cal help you.

AppBarButton exception in Universal WinRT app not triggering unhandled exception event

I have a Universal WinRT app and I'm trying to implement global exception handling so I can prompt the user to send me a report with extra diagnostic information I've collected. (The extra diagnostic information is why I can't use the built-in handler that will log up to the Dev Portal).
I have the following code:
public App() {
InitializeComponent();
UnhandledException += OnUnhandledException;
// other stuff
}
private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) {
try {
//handler
}
catch { }
throw e.Exception;
}
When I force an exception in my initial XAML page (my sign in page), e. g. hard code
throw new FileNotFoundException();
then my handler is triggered as expected. However, if I do this in my main hub page, which my start page navigates to, then it looks like my handler doesn't run. I can see the exception being thrown in the debugger, but it just gets swallowed somewhere. I can't find out where. I should mention that the app happily continues on at this point - it doesn't crash.
I've set DISABLE_XAML_GENERATED_BINDING_DEBUG_OUTPUT and DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION in my Project Properties to disable the built-in overrides, and as far as I know there's no async void situation here (e. g. Unhandled exception handler not called for Metro / WinRT UI async void event handler - although from what I've read, that kind of issue is resolved in 8.1 in any event). But there may be some kind of hidden async void thing going on that I'm not seeing.
I'm sure I'm missing something stupid. What is it?
(EDIT) It appears this is an issue when the exception is in a AppBarButton button event specifically.
(EDIT 2) A somewhat minimum repro is here: http://1drv.ms/1rSNq3i - run this in the 8.1 emulator or on an 8.1 phone, tap the button, open the commandbar, and choose sign out - this should trigger an exception and the handler, but the exception is lost. If you move the code to a button in the same page (a standard button), the handler fires.
(EDIT 3) I tried using the dispatcher in a minimal way, and it didn't change the visible result:
private void SignOutAppBarButton_Click(object sender, RoutedEventArgs e) {
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
throw new FileNotFoundException();
}).AsTask().Wait();
}
In addition to the UnhandledException event you need to handle Frame.NavigationFailed. An exception in a page constructor results in firing NavigationFailed.

Error while unloading appdomain. (Exception from HRESULT: 0x80131015) occurs when closing a form

I am using a login form to get a main form. Login form calls the main when the password is correct. Even if I commanded the login form to close, it doesnt show as closed, it remains minimized in the taskbar. But when i close the main form when its running the exception "Error while unloading appdomain. (Exception from HRESULT: 0x80131015)" is given. Please help.
Winforms doesn't support AppDomains. It bombs because the form won't close. It doesn't even know it exists, it is in another AD. Don't try to make this work, only create forms in the default domain.
This is a reported Microsoft bug. There is a workaround for it - to call reportViewer.LocalReport.ReleaseSandboxAppDomain() method before closing the parent form.
Example:
private void formname_FormClosing(object sender, FormClosingEventArgs e)
{
reportViewername.LocalReport.ReleaseSandboxAppDomain();
}
Modify what happens during the FormClosing event, in there you just have to add reportViewer1.Dispose();
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e);
reportViewer1.Dispose();
}

Why won't Application.Exit() quit a Windows Forms application?

I am working on learning Windows Forms with C# and have a bare bones application. I am trying to close it when the user selects File->Exit. I have an event handler attached to it and I have tried calling Application.Exit(), Application.ExitThread() and just closing the form. Nothing. It stays there. I'm not creating any other threads of any sort either.
Ideas? Thanks.
Have you tried to put a breakpoint in the event handler to see if it is being hit?
If so, the application won't exit if the window messages aren't being delivered (i.e. the UI thread is blocked). One way to test this is to call Environment.Exit() which is more brutal about forcing a close. If this succeeds, you can then figure out why Application.Exit() isn't working.
Application.Exit isn't the normal way to close a GUI application. Use form.Close instead.
private static void OnMenuClose_Click(object sender, System.EventArgs e)
{
Form dlg = ((Control) sender).FindForm();
//dlg.DialogResult = DialogResult.OK;
dlg.Close();
}

Categories