title: How to reliably capture Windows logon, logoff, lock and unlock events from a service?
body: <pre><code>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); 
    } 
  } 
  </code></pre>
  
  <p>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.</p>
  
  <p>When i restart the service it will capture all events as expected. How do I go about troubleshooting/fixing this?</p>