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

12,787

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.

Share:
12,787
Abdul jalil
Author by

Abdul jalil

Updated on June 04, 2022

Comments

  • Abdul jalil
    Abdul jalil almost 2 years
    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?