//当用户试图注销或关闭系统时发生。
SystemEvents.SessionEnding += new SessionEndingEventHandler(SystemEvents_SessionEnding);
//下面是系统注销或关闭事件处理程序,
private void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
{
if (MessageBox.Show(this, "是否允许系统注销!", "系统提示", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
e.Cancel = true;
}
else
{
e.Cancel = false;
}
SessionEndReasons reason = e.Reason;
switch (reason)
{
case SessionEndReasons.Logoff:
MessageBox.Show("用户正在注销。操作系统继续运行,但启动此应用程序的用户正在注销。");
break;
case SessionEndReasons.SystemShutdown:
MessageBox.Show("操作系统正在关闭。");
break;
}
}
//如果把上面的事件处理程序修改成如下
//private void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
// {
// e.Cancel = true;
// }
//那会出现什么情况,你点击开始菜单关机选择注销、关机、或重新启动将会失效,电脑不能正常关机了,进一步的话把程序做成Windows服务,晕,恶作剧?
//SessionEnded
//事件同上,事件参数类为 SessionEndedEventArgs ,同 SessionEndingEventArgs 相比少了Cancel属性,Cancel属性同一些windows下的某些事件差不多,比如Form.Closing事件,Control.Validating事件。
//补充,如果需要获取应用程序需要的系统信息,可以访问 System.Windows.Forms.SystemInformation 类,这也是一个很有用的类,它提供了一组静态属性。