title: Get notified from logon and logoff
body: <p>I have to develop a program which runs on a local pc as a service an deliver couple of user status to a server. At the beginning I have to detect the user <strong>logon</strong> and <strong>logoff</strong>.</p>
  
  <p>My idea was to use the <code>ManagementEventWatcher</code> class and to query the <code>Win32_LogonSession</code> to be notified if something changed. </p>
  
  <p>My first test works well, here is the code part <em>(This would executed as a thread from a service)</em>:</p>
  
  <pre><code>private readonly static WqlEventQuery qLgi = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance ISA \"Win32_LogonSession\"");
  
  public EventWatcherUser() {
  }
  
  public void DoWork() {
      ManagementEventWatcher eLgiWatcher = new ManagementEventWatcher(EventWatcherUser.qLgi);
      eLgiWatcher.EventArrived += new EventArrivedEventHandler(HandleEvent);
      eLgiWatcher.Start();
  }
  
  private void HandleEvent(object sender, EventArrivedEventArgs e)
  {
      ManagementBaseObject f = (ManagementBaseObject)e.NewEvent["TargetInstance"];
      using (StreamWriter fs = new StreamWriter("C:\\status.log", true))
      {
          fs.WriteLine(f.Properties["LogonId"].Value);
      }
  }
  </code></pre>
  
  <p>But I have some understanding problems and I’m not sure if this is the common way to solve that task.</p>
  
  <ol>
  <li><p>If I query <code>Win32_LogonSession</code> I get several records which are
  associated to the same user. For example I get this IDs 7580798 and
  7580829 and if I query </p>
  
  <p>ASSOCIATORS OF {Win32_LogonSession.LogonId=X}
      WHERE ResultClass=Win32_UserAccount</p>
  
  <p>I get the same record for different IDs.
  (Win32_UserAccount.Domain="PC-Name",Name="User1")</p>
  
  <p>Why are there several logon session with the same user? What is the
  common way to get the current signed in user? Or better how to get notified
  correctly by the login of a user?</p></li>
  <li><p>I thought I could use the same way with <code>__InstanceDeletionEvent</code> to
  determine if a user is log off. But I guess if the event is raised, I
  cant query <code>Win32_UserAccount</code> for the username after that. I’m right?</p></li>
  </ol>
  
  <p>I’m at the right direction or are there better ways? It would be awesome if you could help me!</p>
  
  <p><strong>Edit</strong> Is the WTSRegisterSessionNotification class the correct way? I don't know if it's possible, because in a service I haven't a window handler.</p>