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.Shutdown) ReasonSessionEnding.Logoff值之一ReasonSessionEnding

SessionEnding 不会由控制台应用程序引发。

SessionEnding 仅在创建 Application 对象的线程上引发。

SessionEnding 不会引发 XAML 浏览器应用程序 (XBAP) 。

适用于

产品 版本
.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

另请参阅