A WPF login window shown from OnStartup can silently end the whole app the moment it closes. The article measures why OnMainWindowClose fails as well and proposes an OnExplicitShutdown startup sequence instead.
Key points
- The first Window the app instantiates becomes Application.MainWindow, so the login window takes that role.
- With the default OnLastWindowClose the login window is the only window, so shutdown starts before ShowDialog() returns.
- A later Show() does not throw; IsVisible is false immediately and the main window never appears.
- Assigning ShutdownMode after ShowDialog() returns raises InvalidOperationException because shutdown is already running.
- Recommended order: OnExplicitShutdown while the login window is open, then OnMainWindowClose.
- Creating the main window first keeps the process alive on cancel unless Shutdown() is called.
Why it matters
Anyone who has put a sign-in window in front of a WPF shell has met this: nothing throws, the log looks clean, and the process exits anyway. The measurement is the valuable part — both the default OnLastWindowClose and the commonly suggested OnMainWindowClose fail, for different reasons, so the cure is ordering rather than a different enum value.
On .NET 5 or later with an MVVM startup path, check where ShutdownMode is assigned; doing it after ShowDialog() returns is too late and surfaces as InvalidOperationException. The OnExplicitShutdown-then-switch pattern costs a few lines, but it hands the cancel path back to you, so a rejected sign-in has to call Shutdown() explicitly.
Real-world use
- A WPF desktop app that gates its main window behind a sign-in dialog
- An MVVM login view model that only raises CloseRequested instead of touching its own window
- A canceled sign-in where the process must exit rather than linger with a hidden window
This summary was generated by the agent from the original post on S. Iguchi WPF Notes. The full text and all rights belong to its author and publisher. Go to original