2

When my program is being closed (initiated by Application.Shutdown()), I'm catching the Closing event on the main window. In the handler, I create a dialog box asking the user if they want to save their work. In this specific case, the user cannot cancel the application closing event, which is fine by me.

I have found that if I initiate the "want to save" Window via ShowDialog, the window never shows. However, MessageBox.Show does show a window. Is this expected behavior during application shutdown? I can't find anything in the documentation about this behavior. If someone could point me to the relevant documentation or a detailed answer to this question, that would be great.

skybluecodeflier
  • 1,339
  • 13
  • 26

2 Answers2

4

Application.Shutdown ultimately stops the message loop (Dispatcher) for your application. Nothing UI will occur after that. The only reason MessageBox.Show works is because it creates its own internal message loop on the active window of the application.

hoodaticus
  • 3,772
  • 1
  • 18
  • 28
  • 1
    Well that would make some sense then. Is there anything in the documentation about this? – skybluecodeflier Jun 27 '17 at 22:14
  • @skybluecodeflier Of course - the .NET source code. Here's the line where Application.Shutdown, after a few method calls, eventually gets to Dispatcher.CriticalInvokeShutdown. http://referencesource.microsoft.com/#PresentationFramework/Framework/System/Windows/Application.cs,2502 – hoodaticus Jun 27 '17 at 22:18
1

If you use Application.Current.MainWindow.Close(); that will allow you to use e.Cancel = true;, after which if you use Application.Current.Shutdown(); it will ignore the cancel flag and close the window.

This is assuming you're only using one window, and of course will need to not show your prompt a second time.

Something like:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    e.Cancel = true;

    DisplayCloseConfirmation();
}

Edited based on comments

Michael Woolsey
  • 803
  • 8
  • 15
  • 1
    Actually, this is not possible, as setting e.Cancel = true in a window closing event during application shutdown is ignored. See https://msdn.microsoft.com/en-us/library/ms597013(v=vs.110).aspx – skybluecodeflier Jun 27 '17 at 23:31
  • Ahhh, right. My bad, I am using `Application.Current.MainWindow.Close();` initially to allow my application to close with a prompt. Thank you for pointing that out! :) – Michael Woolsey Jun 28 '17 at 13:33