How to use Application.Exit Event in WPF?
Asked Answered
S

5

28

I need to delete some certain files, then user closes program in WPF. So I tried MDSN code from here http://msdn.microsoft.com/en-us/library/system.windows.application.exit.aspx this way:

this code located here App.xml.cs

public partial class App : Application
{
 void App_Exit(object sender, ExitEventArgs e)
    {
       MessageBox.Show("File deleted");
        var systemPath = System.Environment.GetFolderPath(
                                  Environment.SpecialFolder.CommonApplicationData);

                var _directoryName1 = Path.Combine(systemPath, "RadiolocationQ");
                var temp_file = Path.Combine(_directoryName1, "temp.ini");

                if (File.Exists(temp1_file))
                {
                    File.Delete(temp1_file);
                }

    }

}

// App.xaml
<Application x:Class="ModernUIApp1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml"
             ShutdownMode="OnExplicitShutdown"
             Exit="App_Exit">
    <Application.Resources>

First of all it doesn't delete files, secondly this program stays in the process after I pushed exit button( this is really strange). This code don't give any errors. And finally it doesn't show MessageBox So anything wrong here?

I think he just can`t find this function.

Settles answered 3/12, 2013 at 9:1 Comment(3)
Have you wired up the App_Exit event in the XAML?Attemper
@Silvermind anyway nothing happensSettles
If you put a break point in there, does it get hit? Also show us your logic of the Exit button.Mancino
H
67

It's quite simple:

Add "Exit" property to the application tag

<Application x:Class="WpfApplication4.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml"
             Exit="Application_Exit">
</Application>

and handle it in the "code behind"

private void Application_Exit(object sender, ExitEventArgs e)
{
    // Perform tasks at application exit
}

The Exit event is fired when the application is shutting down or the Windows session is ending. It is fired after the SessionEnding event. You cannot cancel the Exit event.

Hybridize answered 3/12, 2013 at 9:26 Comment(4)
Could you look my code one more time, I did exatly like you said, but I get other problemsSettles
I tied it and it's working fine. what is your issue? give me more details. try to remove the property ShutdownMode="OnExplicitShutdown" and let me know if it worksHybridize
I have removed ShutdownMode="OnExplicitShutdown" and it started to work properly. Thank you a lot.Settles
That not how you are supposed to do it. Just protected override void OnExit(ExitEventArgs e) in the code behind. Register to class own events is avoidable, avoid it.Elemi
M
13

you should add app_exit in your xaml code

 <Application x:Class="CSharp.App"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  StartupUri="MainWindow.xaml" 
  ShutdownMode="OnExplicitShutdown"
  Exit="App_Exit"
    >
</Application>

you can just hook the event Closing on your main window like this -

 <Window Closing="Window_Closing">

And in your event do all the work you need

    private void Window_Closing(object sender, CancelEventArgs e)
{
     MessageBox.Show("File deleted");
    var systemPath = System.Environment.GetFolderPath(
                              Environment.SpecialFolder.CommonApplicationData);

            var _directoryName1 = Path.Combine(systemPath, "RadiolocationQ");
            var temp_file = Path.Combine(_directoryName1, "temp.ini");

            if (File.Exists(temp1_file))
            {
                File.Delete(temp1_file);
            }
}
Martinet answered 3/12, 2013 at 9:3 Comment(1)
Yes I forget to add app_exit event, but here new problem appeared. I updated questionSettles
C
7

If you don't like adding Exit event to XAML, you could try this alternative.

Add following method to your App.xaml.cs:

protected override void OnExit(ExitEventArgs e)
{
    base.OnExit(e);
    // Your code here
}
Colettecoleus answered 11/11, 2019 at 18:29 Comment(1)
Beware that base.OnExit(e); is what invokes the exit event.Hirsutism
G
5

If you want to follow MVVM principle you can use System.Windows.Interactivity.WPF.

MainWindow.xaml

<Window x:Class="Endonext.View.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Closing">
        <i:InvokeCommandAction Command="{Binding WindowClosingCommand, Mode=OneTime}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

MainWindowViewModel.cs

public class MainWindowViewModel 
{
    ICommand WindowClosingCommand => new RelayCommand(arg => this.WindowClosing());

    private void WindowClosing()
    {
      // do what you want.
    }
}

This approach is more testable. Have a nice day.

Grig answered 15/2, 2019 at 9:5 Comment(2)
Please note: #46556740Essonite
You also need to implement RelayCommand in order for this solution to work.Essonite
C
0
  1. Make sure that the namespace (MyApp) matches "x:Class=MyApp..."
  2. Under properties for <Application></Application>, double click on the textbox next to 'Exit'.
  3. If you get "Unable to add event handler" then Rebuilding the project fixed it for me.

XAML

<Application x:Class="MyApp.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml"
         Exit="Application_Exit"
>

Code behind

using System.Windows;

namespace MyApp
{ 
   public partial class App : Application
   {
     private void Application_Exit(object sender, ExitEventArgs e)
     {
         //your code
     }
  }
}
Camelot answered 19/9, 2017 at 16:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.