WPF
application development
C#
.NET
programming tips

How do I exit a WPF application programmatically?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Exiting a WPF (Windows Presentation Foundation) application programmatically is a common requirement in desktop application development. Microsoft provides several ways to achieve this, each with its own use case and best practices. Below, we'll explore the various methods and their technical nuances.

Overview of Application Shutdown in WPF

  1. Application Shutdown Modes: WPF's Application class provides two main shutdown modes:
    • OnMainWindowClose (default) - The application shuts down when the main window is closed.
    • OnExplicitShutdown - The application runs until Shutdown() is called explicitly.
  2. Event Handlers: It is crucial to handle certain events when shutting down, such as Application.Exit and Window.Closing, to ensure resources are managed properly.

Methods to Exit a WPF Application

1. Application.Current.Shutdown()

The Shutdown() method is the most direct way to programmatically exit a WPF application. You can call it from anywhere in your application to trigger a shutdown sequence.

csharp
Application.Current.Shutdown();

Usage Scenarios

  • When you want to close the application after a specific operation completes.
  • Useful in automation scripts or controlled application termination scenarios.

2. Setting the Main Window to null

Alternative to directly calling Shutdown(), setting the main window to null can also trigger a shutdown if the shutdown mode is OnMainWindowClose.

csharp
Application.Current.MainWindow = null;

Usage Scenarios

  • Suitable for de-coupling logic and UI management by managing window states explicitly.

3. Environment.Exit()

This method stops all application threads and exits the program, returning a specified exit code to the operating system. However, it bypasses the normal WPF shutdown sequence.

csharp
System.Environment.Exit(0);

Usage Scenarios

  • Use only if you need to exit immediately and do not require WPF's cleanup processes.
  • Not recommended for regular use due to abrupt termination which may cause resource leaks.

4. Exiting from Within a Window

You can directly close a window, which consequently may lead to application shutdown depending on the shutdown mode.

csharp
this.Close();

Use this within the context of a Window derived class.

Usage Scenarios

  • When operations specific to the window determine closure.
  • Ensures each window manages its own lifecycle appropriately.

5. Custom Logic in OnExit

Customize the shutdown procedure by overriding the OnExit method in your App.xaml.cs.

csharp
1protected override void OnExit(ExitEventArgs e)
2{
3    // Add custom logic before exit
4    base.OnExit(e);
5}

Usage Scenarios

  • To perform logging, cleanup, and other tasks upon application exit.

Handling Events During Shutdown

Application.Exit

Use the Application.Exit event to handle one-time cleanup logic before the application shuts down.

csharp
1Application.Current.Exit += (sender, e) =>
2{
3    // Cleanup code
4};

Window.Closing

The Window.Closing event allows you to cancel the close operation if necessary, and perform any necessary validation or prompts.

csharp
1this.Closing += (sender, e) =>
2{
3    // Logic to determine if closing should proceed
4    if (!ShouldClose())
5    {
6        e.Cancel = true;
7    }
8};

Summary Table

MethodDescriptionUse Case
Application.Current.Shutdown()Gracefully shuts down the application.Most common and recommended approach.
Application.Current.MainWindow = null;Triggers shutdown under OnMainWindowClose mode.When managing windows manually.
System.Environment.Exit(0);Immediately exits all threads and processes.Only when immediate exit is necessary.
this.Close();Closes the window, which might exit the app.Window-specific logic initiated closure.

Conclusion

In most cases, Application.Current.Shutdown() is the most appropriate method to terminate a WPF application, ensuring that the normal cleanup processes are honored. It is, however, essential to choose the method that aligns best with your application's architecture and requirements. Remember to handle exit events to manage resources effectively and provide a smooth user experience.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.