private void Form1_Load(object sender, EventArgs e)
{
startLisning();
}
private bool eventHandlerCreated;
private void startLisning()
{
Microsoft.Win32.SystemEvents.SessionSwitch +=new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch1);
this.eventHandlerCreated = true;
}
private void SystemEvents_SessionSwitch1(object sender, SessionSwitchEventArgs e)
{
switch (e.Reason)
{
case SessionSwitchReason.SessionLock:
System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "LOCK\t" + DateTime.Now.ToString() + Environment.NewLine);
break;
case SessionSwitchReason.SessionLogon:
System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "LOGIN\t" + DateTime.Now.ToString() + Environment.NewLine);
break;
case SessionSwitchReason.SessionUnlock:
System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "UNLOCK\t" + DateTime.Now.ToString() + Environment.NewLine);
break;
case SessionSwitchReason.ConsoleConnect:
System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "UnlockAfetSwitchUser\t" + DateTime.Now.ToString() + Environment.NewLine);
break;
case SessionSwitchReason.ConsoleDisconnect:
System.IO.File.AppendAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "testtest.txt"), "SwitchUser\t" + DateTime.Now.ToString() + Environment.NewLine);
break;
}
}
这将在“切换用户”发生时通知,并在“用户恢复”时通知。'SessionSwitchReason.ConsoleDisconnect' 是任何切换用户发生时触发的事件。此代码已在 windows7 中测试,并且运行良好。
此代码在 Appdata 文件夹中创建一个“testtest.txt”日志文件。你可以通过使用 Window+r 并搜索 '%appdata%' 到达那里。
它记录通知如下: 1. 使用日期时间登录 2. 使用日期时间锁定 3. 使用日期时间解锁 4. 使用日期时间切换用户 5. 使用日期时间切换用户恢复