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;
}
}
This will notify when "switch user" happen and also notify when the "user resume" .
'SessionSwitchReason.ConsoleDisconnect' is the event which fire when any switch user happen . This code is tested in windows7 and it working fine.
This code create a "testtest.txt" log file in Appdata folder. U can reach there by using Window+r and search '%appdata%'.
It log notification as below :
1. LOGIN with datetime
2. LOCK with datetime
3. UNLOCK with datetime
4. SWITCH USER with datetime
5. SWITCH USER RESUME with datetime