Hi,
Once I was asked if there is a way to detect system/workstation state and log the details in a file. So, i came up with the below sample code. I want to give credit to a folk from whom i got the idea about it. I hope it helps you in some way.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.Win32;
namespace DetectWorkstation
{
class Program
{
public void LogSystemLoginDetails()
{
SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
}
static void Main(string[] args)
{
Program p = new Program();
p.LogSystemLoginDetails();
Console.ReadLine();
}
void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
FileStream fs = new FileStream("D:\\SessionLog.txt", FileMode.Append, FileAccess.Write);
StreamWriter sr = new StreamWriter(fs);
sr.Write("Locked at: " + System.DateTime.Now.ToLongDateString() + "\t Time: " + System.DateTime.Now.ToLongTimeString() + Environment.NewLine);
sr.Flush();
sr.Close();
}
if (e.Reason == SessionSwitchReason.SessionUnlock)
{
FileStream fs1 = new FileStream("D:\\SessionLog.txt", FileMode.Append, FileAccess.Write);
StreamWriter sr1 = new StreamWriter(fs1);
sr1.Write("Unlocked at: " + System.DateTime.Now.ToLongDateString() + "\t Time: " + System.DateTime.Now.ToLongTimeString() + Environment.NewLine);
sr1.Flush();
sr1.Close();
}
}
}
}
Please comment your views.
Thanks
No comments:
Post a Comment