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」日誌文件。 U可以通過使用Window + r並搜索'%appdata%'來到達那裏。
它登錄如下通知: 1. LOGIN與日期時間 2. LOCK與日期時間 3. UNLOCK與日期時間 與日期時間
日期時間 5. SWITCH USER RESUME 4. SWITCH USER