Application.SessionEnding 事件

定義

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

C#
public event System.Windows.SessionEndingCancelEventHandler SessionEnding;

事件類型

範例

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

XAML
<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" />
C#
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;
            }
        }
    }
}

備註

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

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

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

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

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

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

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

適用於

產品 版本
.NET Framework 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另請參閱