Application.Exit Application.Exit Application.Exit Application.Exit Event

Определение

Генерируется непосредственно перед завершением работы приложения и не может быть отменено.Occurs just before an application shuts down, and cannot be canceled.

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

Примеры

В следующем примере показано, как:The following example demonstrates how to:

  • Обработайте Exit событие.Handle the Exit event.

  • Проверьте и обновите ApplicationExitCode свойство ExitEventArgsобъекта.Inspect and update the ApplicationExitCode property of the ExitEventArgs.

  • Запись записи в журнал приложения в изолированном хранилище.Write an entry to an application log in isolated storage.

  • Сохранение состояния приложения в изолированном хранилище.Persist the application state to isolated storage.

<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

Комментарии

Приложение может завершить работу по одной из следующих причин:An application can shut down for either of the following reasons:

  • Метод объекта вызывается либо явным образом, либо в соответствии со ShutdownMode свойством. Application ShutdownThe Shutdown method of the Application object is called, either explicitly or as determined by the ShutdownMode property.

  • Пользователь завершает сеанс путем выхода из системы или завершения его работы.The user ends the session by logging off or shutting down.

Можно определить, когда происходит завершение работы приложения, обрабатывая Exit событие, и при необходимости выполнить дополнительную обработку.You can detect when application shutdown occurs by handling the Exit event, and perform any additional processing as required.

Кроме того Exit , можно выполнять проверку или изменение кода выхода приложения, если вам не нужно вызывать Shutdown его явным образом.You can also handle Exit to inspect or change the application exit code when you don't need to call Shutdown explicitly. Код выхода предоставляется из ApplicationExitCode свойства ExitEventArgs аргумента Exit , который передается в обработчик событий.The exit code is exposed from the ApplicationExitCode property of the ExitEventArgs argument that's passed to the Exit event handler. При остановке работы приложения код выхода передается в операционную систему для последующей обработки.When the application stops running, the exit code is passed to the operating system for subsequent processing.

Если приложение обрабатывает SessionEnding событие, а затем отменяет его, Exit не вызывается и приложение продолжит выполнение в соответствии с режимом завершения работы.If your application handles the SessionEnding event and subsequently cancels it, Exit is not raised and the application continues running in accordance with the shutdown mode.

Код выхода можно задать из Приложение обозревателя XAML (XBAP)XAML browser application (XBAP), хотя значение игнорируется.The exit code can be set from an Приложение обозревателя XAML (XBAP)XAML browser application (XBAP), although the value is ignored.

Для XBAPXBAPs ,Exit вызывается в следующих случаях:For XBAPXBAPs, Exit is raised in the following circumstances:

  • XBAPXBAP Выполняется переход от.An XBAPXBAP is navigated away from.

  • В Internet Explorer 7Internet Explorer 7при закрытии вкладки, на которой XBAPXBAP размещается.In Internet Explorer 7Internet Explorer 7, when the tab that is hosting the XBAPXBAP is closed.

  • Закрывается браузер.When the browser is closed.

Во всех случаях значение ApplicationExitCode свойства игнорируется.In all cases, the value of the ApplicationExitCode property is ignored.

Применяется к

Дополнительно