Application.SessionEnding 事件

定義

當使用者登出或關閉作業系統而結束 Windows 工作階段時發生。

public:
 event System::Windows::SessionEndingCancelEventHandler ^ SessionEnding;
public event System.Windows.SessionEndingCancelEventHandler SessionEnding;
member this.SessionEnding : System.Windows.SessionEndingCancelEventHandler 
Public Custom Event SessionEnding As SessionEndingCancelEventHandler 

事件類型

範例

下列範例示範如何處理 SessionEnding 事件,並允許使用者取消事件。

<Application 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.App"
    StartupUri="MainWindow.xaml"
    SessionEnding="App_SessionEnding" />
using System.Windows;

namespace SDKSample
{
    public partial class App : Application
    {
        void App_SessionEnding(object sender, SessionEndingCancelEventArgs e)
        {
            // Ask the user if they want to allow the session to end
            string msg = string.Format("{0}. End session?", e.ReasonSessionEnding);
            MessageBoxResult result = MessageBox.Show(msg, "Session Ending", MessageBoxButton.YesNo);

            // End session, if specified
            if (result == MessageBoxResult.No)
            {
                e.Cancel = true;
            }
        }
    }
}

Imports System.Windows

Namespace SDKSample
    Partial Public Class App
        Inherits Application
        Private Sub App_SessionEnding(ByVal sender As Object, ByVal e As SessionEndingCancelEventArgs)
            ' Ask the user if they want to allow the session to end
            Dim msg As String = String.Format("{0}. End session?", e.ReasonSessionEnding)
            Dim result As MessageBoxResult = MessageBox.Show(msg, "Session Ending", MessageBoxButton.YesNo)

            ' End session, if specified
            If result = MessageBoxResult.No Then
                e.Cancel = True
            End If
        End Sub
    End Class
End Namespace

備註

根據預設,應用程式會在 Windows 會話結束時關閉,當使用者登出或關閉時就會發生此情況。 發生這種情況時,Windows 會要求每個開啟的應用程式關閉。 不過,當發生這種情況時,應用程式可能尚未準備好關閉。 例如,應用程式可能有處於不一致狀態或長時間執行作業中間的資料。 在這些情況下,可能會想要防止會話結束,而且可能更想要讓使用者選擇是否讓會話結束。

您可以藉由處理 SessionEnding 事件來偵測會話何時結束。 如果應用程式需要防止會話結束, SessionEndingCancelEventArgs 傳遞至事件處理常式的引數會公開 Cancel 您設定為 true 的 , (預設值為 false) 。

如果 SessionEnding 未處理,或是在未取消的情況下處理, Shutdown 則會呼叫 並 Exit 引發 事件。

若要取得會話結束原因的詳細資訊,應用程式可以檢查 ReasonSessionEnding ,這是其中一個 ReasonSessionEnding 值 (ReasonSessionEnding.LogoffReasonSessionEnding.Shutdown) 。

SessionEnding 不會由主控台應用程式引發。

SessionEnding 只會在建立 物件的執行緒上引發 Application

SessionEnding 不會針對 XBAP) (XAML 瀏覽器應用程式引發。

適用於

另請參閱