Amit

Amit

  • NA
  • 1
  • 3.1k

Logging lock/unlock/logoff/logon events using Windows Service NOT working

Apr 20 2012 1:12 AM
I have created a windows service as follows:
_________________________________________________________________
public partial class UserMonitorService : ServiceBase
{
 
public UserMonitorService()
{
InitializeComponent();
}
 
void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
switch (e.Reason)
{
case SessionSwitchReason.SessionLock:
LogEntry(string.Format("Locked at {0}", DateTime.Now));
break;
case SessionSwitchReason.SessionLogoff:
LogEntry(string.Format("Logged Off at {0}", DateTime.Now));
break;
case SessionSwitchReason.SessionLogon:
LogEntry(string.Format("Logged On at {0}", DateTime.Now));
break;
case SessionSwitchReason.SessionUnlock:
LogEntry(string.Format("Unlocked at {0}", DateTime.Now));
break;
default:
break;
}
}
 
protected override void OnStart(string[] args)
{
LogEntry(string.Format("Service Started at {0}", DateTime.Now));
SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
}
 
protected override void OnStop()
{
LogEntry(string.Format("Service Stopped at {0}", DateTime.Now));
}
 
void LogEntry(string message)
{
StreamWriter sw = new StreamWriter("D:/ServiceLog.txt",true);
sw.WriteLine(message);
sw.Close();
}
 
}
_________________________________________________________________
 
After installing, it logs Service start and stop messages perfectly, but does not log any of the session related events (so I know that problem is NOT with the logging part here).
Also, when I create a Console Application using the same code and execute it, it logs session lock/unlock events too (so I know that the SessionSwitch handler is also correct).
 
So what is the mistake here? Am I missing some windows service configuration change that needs to be done here? Thanks in advance.