Archive

Archive for September, 2014

Microsoft.Win32.SystemEvents in Winform

September 10, 2014 Leave a comment

You can catch You machine logon\logoff event in .Net

using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.IO;
namespace WindowsFormsApplication1
{
public class SessionEvent
{
public SessionEvent()
{
SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
Microsoft.Win32.SystemEvents.SessionEnding += SystemEvents_SessionEnding;
}

void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
{
string path = @”C:\Datafeed\Example.txt”;
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(e.Reason + ” ” + DateTime.Now.ToString());
tw.Close();
}
else if (File.Exists(path))
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(e.Reason + ” ” + DateTime.Now.ToString());
}
}
}

~SessionEvent()
{
//Do this during application close to avoid handle leak
Microsoft.Win32.SystemEvents.SessionSwitch -= new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
}

private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLogon ||
e.Reason == SessionSwitchReason.SessionLogoff ||
e.Reason == SessionSwitchReason.SessionLock ||
e.Reason == SessionSwitchReason.SessionUnlock)
{
string path = @”C:\Datafeed\Example.txt”;
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(e.Reason + ” ” + DateTime.Now.ToString());
tw.Close();
}
else if (File.Exists(path))
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(e.Reason + ” ” + DateTime.Now.ToString());
}
}
}

}

}
}

Categories: C#