1. 在MainForm中定义注销、关机事件处理方法
示例MainForm.cs:
using System;
using System.Windows.Forms;
using Microsoft.Win32;
namespace LogoutOrShutdownTest
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
/// <summary>
/// 用户注销或关闭系统的事件处理方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
internal void SessionEnding(object sender, SessionEndingEventArgs e)
{
Console.WriteLine("正在注销或关机...");
}
}
}
2. 绑定注销、关机事件
示例Program.cs:
using System;
using System.Windows.Forms;
using Microsoft.Win32;
namespace LogoutOrShutdownTest
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MainForm mainForm = new MainForm();
//绑定用户注销或关闭系统的事件处理方法
SystemEvents.SessionEnding += mainForm.SessionEnding;
Application.Run(mainForm);
}
}
}