Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reliably capture Windows logon, logoff, lock and unlock events from a service?

using Microsoft.Win32; 

public class App 
{ 
  static void Main() 
  { 
    SystemEvents.SessionSwitch += SystemEvents_SessionSwitch; 
    Console.ReadLine();  
    SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch; 
  } 

  static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e) 
  { 
  if(e.Reason == SessionSwitchReason.SessionLock) 
  { 
    Console.WriteLine("locked at {0}", DateTime.Now); 
  } 
  if(e.Reason == SessionSwitchReason.SessionUnlock) 
  { 
    Console.WriteLine("unlocked at {0}", DateTime.Now); 
  } 
} 

I have created a Windows service. When I restart the system and login, logoff, lock or unlock the session. it will not capture the event. The service is running, but it will not work properly.

When i restart the service it will capture all events as expected. How do I go about troubleshooting/fixing this?

like image 984
Abdul jalil Avatar asked Oct 06 '09 14:10

Abdul jalil


1 Answers

Make your service dependent on TermService (the Terminal Services service). Under the covers, the SystemEvents class is based on the WTSRegisterSessionNotification Win32 function, which is documented to fail if the Terminal Services service hasn't started by the time it's called. By adding the dependency on TermService to your service, that won't happen. You could also connect to the Global\TermSrvReadyEvent global event using a technique like this and wait to register the SystemEvent handler until the TS "ready" event fires.

like image 133
nitzmahone Avatar answered Oct 17 '22 08:10

nitzmahone