I tried to detect logoff event and write it in a text.
How can this be fixed? i wanted to write the logoff time in a text file but the text file is not created when i logoff the PC.
static void Main(string[] args)
{
SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
Console.ReadLine();
SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch;
}
static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLogoff)
{
TextWriter tw = new StreamWriter("D:\\date.txt");
tw.WriteLine("logoff" + DateTime.Now);
tw.Close();
}
if (e.Reason == SessionSwitchReason.SessionLogon)
{
TextWriter tw1 = new StreamWriter("D:\\date.txt");
tw1.WriteLine("logoff" + DateTime.Now);
tw1.Close();
}
}
This won’t work unless the app has a facility for reading Windows messages which your console application doesn’t have. According to the documentation for SystemEvents.SessionSwitch Event:
If you insist on running this as a console app, check Handling Messages in Console Apps which is a tutorial for running the message pump inside a console application.