title: Detect users logging off in Windows service
body: <p>I'm interested in listening to logging off events from a Windows service running in Session 0</p>
  <ul>
  <li>whilst <strong>also knowing which user it is that is logging off (their Session ID)</strong></li>
  <li>Note I'm talking about the cancellable logging off event here, not the logged off event</li>
  </ul>
  <hr />
  <h3>How to find out which user is logging off - getting Session ID from <a href="http://msdn.microsoft.com/en-us/library/Microsoft.Win32.SessionEndingEventArgs_properties.aspx" rel="nofollow noreferrer">SessionEndingEventArgs</a> ?</h3>
  <pre><code>protected override void OnStart(string[] args)
      {
          SystemEvents.SessionEnding += SystemEvents_SessionEnding;
      }
  
  private void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
      {
          // SessionEndingEventArgs does not contain SID
          // or other user identifying info?
      }
  </code></pre>
  <p>[ And I havent tested <a href="http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents.aspx" rel="nofollow noreferrer">whether a Windows Service can actually capture the SessionEnding event</a> ]</p>
  <hr />
  <h3>Or can <a href="http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&amp;l=EN-US&amp;k=k%28System.ServiceProcess.SessionChangeDescription%29;k%28TargetFrameworkMoniker-.NETFramework" rel="nofollow noreferrer">SessionChangeDescription</a> be used to identify users that are about to log off ?</h3>
  <pre><code>public ServiceApp()
      {
          CanHandleSessionChangeEvent = true;
      }
  
  protected override void OnSessionChange(SessionChangeDescription changeDescription)
      {
          // Although changeDescription has SessionId property
          // I'm not sure it has the equivalent of session ending event?
          base.OnSessionChange(changeDescription);
      }
  </code></pre>
  <ul>
  <li>i.e. on <a href="http://msdn.microsoft.com/en-us/library/system.serviceprocess.sessionchangereason.aspx" rel="nofollow noreferrer">SessionLogoff</a> the user has already logged off</li>
  <li>and im not sure when the other events occur e.g. <a href="http://msdn.microsoft.com/en-us/library/system.serviceprocess.sessionchangereason.aspx" rel="nofollow noreferrer">ConsoleDisconnect</a>
  ?</li>
  </ul>
  <hr />
  <h3>Other event sources ?</h3>
  <ul>
  <li>Or does <a href="http://code.google.com/p/cassia/" rel="nofollow noreferrer">Cassia</a> provide such events, including user account information?</li>
  <li>Or can i pull it from WMI somewhere?</li>
  <li>Or use some Win32 API directly?</li>
  </ul>