Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I have created a windows service in c# (to write a log everytime I Login/Lock/Unlock into my machine) and installed it on my machine. But except for service start nothing else is logged.

Here is the code:

protected override void OnStart(string[] args)
{
  SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
  Console.ReadLine();
  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 ");
  }
}


Ajay
Posted
Updated 8-Nov-10 3:03am
v2

1 solution

You should deregister your SessionSwitch eventhandler in the OnStop method. Otherwise while your service is running your handler won't be triggered.

C#
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 ");
  }
}
 
Share this answer
 
v2
Comments
Ajay R Ojha 8-Nov-10 10:39am    
I tried your suggestion but it still doesnt work. I guess it works in console application but not in Windows service.
Eddy Vluggen 8-Nov-10 10:52am    
The service is running under a different account than the user; when the user ends it's session, the service is simply still logged in. In other words, when you logout, the service doesn't.
Ajay R Ojha 8-Nov-10 12:00pm    
wow eddy ... this may be it ... any suggestion as to how i can get out of this pickle ...
Ajay R Ojha 9-Nov-10 4:23am    
Eddy that was it. Its working now. Thanks a lot.
Espen Harlinn 17-Jan-11 11:21am    
5+ Good answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900