Closing a Windows Presentation Foundation (WPF) application in C# can mean closing one window, shutting down the entire application, or responding to a user’s request to exit. Choosing the right approach matters: closing a window may leave other windows running, while shutting down the application ends its message loop and closes all open windows. This guide explains how to close a WPF window, exit the whole application, handle confirmation prompts, and avoid common shutdown problems.
Choose Between Closing a Window and Shutting Down the Application
Start by deciding what should happen when the user selects an Exit button or clicks a window’s close button. If only the current window should close, call its Close() method. If the entire WPF application should exit, call Application.Current.Shutdown().
-
Close one window: Use
Close()on the relevantWindowinstance. -
Exit the application: Use
Application.Current.Shutdown(). -
Hide a window temporarily: Use
Hide()if the window should remain available to show again.
These actions are not interchangeable. Closing a window ends that window’s lifetime, and it cannot simply be shown again. Hiding a window keeps the same instance alive. Shutting down the application ends the WPF application, including its windows and dispatcher.
Close the Current WPF Window with Close()
To close the window containing a button, call Close() in the button’s click handler. This is a common choice for a dialog, settings window, or secondary window that should close without necessarily ending the entire application.
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
Close();
}
Inside a window class, Close() refers to that window instance. You can also call the method explicitly through a named window reference, such as settingsWindow.Close(). If a window is opened with ShowDialog(), closing it ends the modal dialog and returns control to the window that opened it.
After a window has been closed, its instance is no longer usable as an open window. If the user needs to open it again, create a new instance rather than trying to show the closed one.
Exit the Entire Application with Application.Current.Shutdown()
When an Exit command should end the whole WPF application, call Shutdown() on the current application object. This is usually the clearest and safest way to request a normal application shutdown.
private void ExitButton_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
WPF then performs its normal shutdown sequence. Open windows receive their closing notifications, allowing their Closing handlers to run. The application’s Exit event is raised as shutdown completes. Because a closing handler can cancel the process, calling Shutdown() is a request to shut down, not a way to bypass the application’s normal closing logic.
You can also provide an exit code when appropriate:
Application.Current.Shutdown(0);
The exit code is useful when another process or script needs to interpret how the application ended. A value of zero commonly indicates a normal exit, although the meaning of particular values is up to your application.
Understand WPF ShutdownMode
The application’s ShutdownMode setting determines when WPF shuts down automatically. It is configured in App.xaml or in application code. Understanding this setting can explain why an application exits when a window closes—or why it stays running when you expected it to quit.
- OnLastWindowClose: The application shuts down when the last open window closes. This is the default behavior.
- OnMainWindowClose: The application shuts down when its main window closes, even if other windows remain open.
-
OnExplicitShutdown: The application stays running until code explicitly calls
Application.Current.Shutdown().
For example, set the mode in App.xaml like this:
<Application x:Class="MyApp.App"
ShutdownMode="OnMainWindowClose"
StartupUri="MainWindow.xaml">
</Application>
Use OnLastWindowClose when closing the final window should end the program. Choose OnMainWindowClose if secondary windows should not keep the application alive after the main window closes. Select OnExplicitShutdown for applications such as a system-tray utility that may run without any visible windows. With that mode, ensure your code provides a clear way to call Shutdown(), or the process may continue running indefinitely.
Ask for Confirmation Before Closing
Use the window’s Closing event when you need to confirm an exit, check for unsaved work, or prevent a window from closing under certain conditions. The event provides a CancelEventArgs object. Set its Cancel property to true to keep the window open.
private void Window_Closing(object sender, CancelEventArgs e)
{
MessageBoxResult result = MessageBox.Show(
"Are you sure you want to exit?",
"Confirm exit",
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (result != MessageBoxResult.Yes)
{
e.Cancel = true;
}
}
Connect the handler in XAML:
<Window
...
Closing="Window_Closing">
Or subscribe to the event in code. Remember to include the namespace for CancelEventArgs if it is not already available:
using System.ComponentModel;
Use confirmation prompts thoughtfully. Showing one for every small child window can make an application frustrating. A prompt is most useful when closing would discard unsaved changes or interrupt important work.
Prevent Closing When There Is Unsaved Work
A common WPF pattern is to track whether the user has changed a document. When the window is closing, ask whether to save, discard, or cancel. If the user cancels, set e.Cancel to true. If saving fails, you may also want to keep the window open so the user can address the problem.
private bool _hasUnsavedChanges;
private void Window_Closing(object sender, CancelEventArgs e)
{
if (!_hasUnsavedChanges)
{
return;
}
MessageBoxResult result = MessageBox.Show(
"Save your changes before closing?",
"Unsaved changes",
MessageBoxButton.YesNoCancel,
MessageBoxImage.Warning);
if (result == MessageBoxResult.Cancel)
{
e.Cancel = true;
return;
}
if (result == MessageBoxResult.Yes)
{
SaveDocument();
}
}
In a larger application, keep saving and document-state logic outside the window code-behind where practical. A view model can expose commands and state, while the view coordinates window-specific behavior such as closing. The key requirement remains the same: decide whether to cancel the close before the window is destroyed.
Close a Window from Another Window
If one window needs to close another, keep a reference to the target window and call its Close() method. For example, a parent window can close a settings window that it created:
private SettingsWindow? _settingsWindow;
private void OpenSettings_Click(object sender, RoutedEventArgs e)
{
_settingsWindow = new SettingsWindow();
_settingsWindow.Show();
}
private void CloseSettings_Click(object sender, RoutedEventArgs e)
{
_settingsWindow?.Close();
_settingsWindow = null;
}
Another option is to set the child window’s Owner property. Ownership is useful for related windows because it helps WPF manage their relationship and behavior. However, do not assume that closing an owner always means every application window will close; the final result still depends on your shutdown mode and application design.
For larger applications, avoid having unrelated windows reach into each other’s fields. A shared service, event, or other deliberate communication pattern can make window lifetime easier to manage and test.
Close or Shut Down from a Background Thread
WPF user-interface objects are associated with the dispatcher thread that created them. If background work needs to close a window or shut down the application, marshal the operation to the UI dispatcher. Attempting to access a window from the wrong thread can cause a cross-thread access exception.
Application.Current.Dispatcher.Invoke(() =>
{
Application.Current.Shutdown();
});
If the work should continue without blocking its calling thread, use BeginInvoke instead:
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
Application.Current.Shutdown();
}));
In many applications, it is better for background work to report completion or failure to the UI layer, which then decides whether to close the window. This keeps thread coordination and application-lifetime decisions clear.
Clean Up Resources During Application Shutdown
Use window closing or application exit events to release resources your application owns. Examples include stopping timers, unsubscribing from long-lived events, flushing logs, and cancelling background operations. Prefer orderly cancellation and disposal over abruptly terminating the process.
For example, an application can subscribe to its Exit event in App.xaml.cs:
public partial class App : Application
{
protected override void OnExit(ExitEventArgs e)
{
// Release application-level resources here.
base.OnExit(e);
}
}
Do not rely on a particular cleanup event to run after a forced process termination. If reliable persistence matters, save important data during normal application activity rather than waiting until the final shutdown moment.
Methods to Avoid for Normal WPF Shutdown
It may be tempting to use a forceful method to make the process disappear, but these approaches can skip normal WPF behavior and cause data loss or unfinished cleanup.
-
Avoid
Environment.Exit()for routine closing. It terminates the process directly and can bypass normal application shutdown events and window-closing logic. - Avoid killing the current process. Process termination is abrupt and is not a substitute for closing windows or cancelling work correctly.
-
Do not use
Hide()when you intend to exit. Hiding a window leaves it alive and can keep the application running. -
Do not assume closing any window exits the program. The result depends on open windows and the configured
ShutdownMode.
For normal user-driven shutdown, use Close() for a particular window or Application.Current.Shutdown() for the application, and let WPF process the request.
Common WPF Application Closing Scenarios
These quick examples can help you select the right approach:
-
An Exit button on the main window: Call
Application.Current.Shutdown()if the button should end the entire program. -
A Cancel button on a dialog: Call
Close()to dismiss that dialog. -
A tray application: Hide the main window when the user minimizes to the tray, then call
Shutdown()from an explicit Exit command. -
A document with unsaved edits: Handle the
Closingevent and cancel closing if the user chooses not to proceed. - A background task that has finished: Dispatch the close or shutdown request to the UI thread.
Conclusion
To close a WPF application in C#, use Close() when you want to close a specific window and Application.Current.Shutdown() when you want to exit the application. Check the ShutdownMode setting to understand when WPF exits automatically, and handle the Closing event when you need confirmation or must protect unsaved work. For a reliable shutdown, perform UI operations on the dispatcher thread and clean up resources through normal application events instead of forcing the process to terminate.
Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.