You should deregister your SessionSwitch eventhandler in the OnStop method. Otherwise while your service is running your handler won't be triggered.
protected override void OnStart(string[] args)
{
SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
Console.ReadLine();
}
protected override void OnStop()
{
SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch;
}
static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
WriteToLogFile( e.Reason.ToString());
if (e.Reason == SessionSwitchReason.SessionLock)
{
WriteToLogFile("SessionLock ");
}
if (e.Reason == SessionSwitchReason.SessionUnlock)
{
WriteToLogFile("SessionUnlock ");
}
if (e.Reason == SessionSwitchReason.SessionLogon)
{
WriteToLogFile("SessionLogon ");
}
}