Application.Exit Evento

Definição

Ocorre logo antes de um aplicativo ser desligado e não pode ser cancelado.

public:
 event System::Windows::ExitEventHandler ^ Exit;
public event System.Windows.ExitEventHandler Exit;
member this.Exit : System.Windows.ExitEventHandler 
Public Custom Event Exit As ExitEventHandler 

Tipo de evento

Exemplos

O exemplo a seguir demonstra como:

  • Manipule o Exit evento.

  • Inspecione e atualize a ApplicationExitCode propriedade do ExitEventArgs.

  • Gravar uma entrada em um log de aplicativo no armazenamento isolado.

  • Persista o estado do aplicativo para o armazenamento isolado.

<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>
using System;
using System.Collections;
using System.Windows;
using System.IO;
using System.IO.IsolatedStorage;

namespace CSharp
{
    public enum ApplicationExitCode
    {
        Success = 0,
        Failure = 1,
        CantWriteToApplicationLog = 2,
        CantPersistApplicationState = 3
    }

    public partial class App : Application
    {
        void App_Exit(object sender, ExitEventArgs e)
        {
            try
            {
                // Write entry to application log
                if (e.ApplicationExitCode == (int)ApplicationExitCode.Success)
                {
                    WriteApplicationLogEntry("Failure", e.ApplicationExitCode);
                }
                else
                {
                    WriteApplicationLogEntry("Success", e.ApplicationExitCode);
                }
            }
            catch
            {
                // Update exit code to reflect failure to write to application log
                e.ApplicationExitCode = (int)ApplicationExitCode.CantWriteToApplicationLog;
            }

            // Persist application state
            try
            {
                PersistApplicationState();
            }
            catch
            {
                // Update exit code to reflect failure to persist application state
                e.ApplicationExitCode = (int)ApplicationExitCode.CantPersistApplicationState;
            }
        }

        void WriteApplicationLogEntry(string message, int exitCode)
        {
            // Write log entry to file in isolated storage for the user
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly();
            using (Stream stream = new IsolatedStorageFileStream("log.txt", FileMode.Append, FileAccess.Write, store))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                string entry = string.Format("{0}: {1} - {2}", message, exitCode, DateTime.Now);
                writer.WriteLine(entry);
            }
        }

        void PersistApplicationState()
        {
            // Persist application state to file in isolated storage for the user
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly();
            using (Stream stream = new IsolatedStorageFileStream("state.txt", FileMode.Create, store))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                foreach (DictionaryEntry entry in this.Properties)
                {
                    writer.WriteLine(entry.Value);
                }
            }
        }
    }
}

Imports System.Collections
Imports System.Windows
Imports System.IO
Imports System.IO.IsolatedStorage

Namespace VisualBasic
    Public Enum ApplicationExitCode
        Success = 0
        Failure = 1
        CantWriteToApplicationLog = 2
        CantPersistApplicationState = 3
    End Enum

    Partial Public Class App
        Inherits Application
        Private Sub App_Exit(ByVal sender As Object, ByVal e As ExitEventArgs)
            Try
                ' Write entry to application log
                If e.ApplicationExitCode = CInt(ApplicationExitCode.Success) Then
                    WriteApplicationLogEntry("Failure", e.ApplicationExitCode)
                Else
                    WriteApplicationLogEntry("Success", e.ApplicationExitCode)
                End If
            Catch
                ' Update exit code to reflect failure to write to application log
                e.ApplicationExitCode = CInt(ApplicationExitCode.CantWriteToApplicationLog)
            End Try

            ' Persist application state
            Try
                PersistApplicationState()
            Catch
                ' Update exit code to reflect failure to persist application state
                e.ApplicationExitCode = CInt(ApplicationExitCode.CantPersistApplicationState)
            End Try
        End Sub

        Private Sub WriteApplicationLogEntry(ByVal message As String, ByVal exitCode As Integer)
            ' Write log entry to file in isolated storage for the user
            Dim store As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForAssembly()
            Using stream As Stream = New IsolatedStorageFileStream("log.txt", FileMode.Append, FileAccess.Write, store)
                Using writer As New StreamWriter(stream)
                    Dim entry As String = String.Format("{0}: {1} - {2}", message, exitCode, Date.Now)
                    writer.WriteLine(entry)
                End Using
            End Using
        End Sub

        Private Sub PersistApplicationState()
            ' Persist application state to file in isolated storage for the user
            Dim store As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForAssembly()
            Using stream As Stream = New IsolatedStorageFileStream("state.txt", FileMode.Create, store)
                Using writer As New StreamWriter(stream)
                    For Each entry As DictionaryEntry In Me.Properties
                        writer.WriteLine(entry.Value)
                    Next entry
                End Using
            End Using
        End Sub
    End Class
End Namespace

Comentários

Um aplicativo pode ser desligado por um dos seguintes motivos:

  • O Shutdown método do Application objeto é chamado, explicitamente ou conforme determinado pela ShutdownMode propriedade .

  • O usuário encerra a sessão fazendo logoff ou desligando.

Você pode detectar quando o desligamento do aplicativo ocorre manipulando o Exit evento e executar qualquer processamento adicional conforme necessário.

Você também pode manipular Exit para inspecionar ou alterar o código de saída do aplicativo quando não precisa chamar Shutdown explicitamente. O código de saída é exposto da ApplicationExitCode propriedade do ExitEventArgs argumento que é passado para o Exit manipulador de eventos. Quando o aplicativo para de ser executado, o código de saída é passado para o sistema operacional para processamento subsequente.

Se o aplicativo manipular o SessionEnding evento e, posteriormente, cancelá-lo, Exit não será gerado e o aplicativo continuará em execução de acordo com o modo de desligamento.

O código de saída pode ser definido de um XBAP (aplicativo de navegador XAML), embora o valor seja ignorado.

Para XBAPs, Exit é gerado nas seguintes circunstâncias:

  • Um XBAP é navegado para longe.

  • Na Internet Explorer 7, quando a guia que hospeda o XBAP é fechada.

  • Quando o navegador é fechado.

Em todos os casos, o valor da ApplicationExitCode propriedade é ignorado.

Aplica-se a

Confira também