title: How to get token of logged-in user from within windows service with C++?
body: <p>on windows vista &amp; above,</p>
  
  <p>currently, I am enumerating all windows sessions, then once I find an active session, WTSQueryUserToken() is called which gives me the token of current user. </p>
  
  <p>This token is used to launch a process with his privileges / inside his desktop.</p>
  
  <p>Problem I am facing is that there is not reliable way to get the active session / interactive session. I have to wait (check its presence every few millsecs) until explorer.exe is spawned.</p>
  
  <p>I am not preferring notifications like those from SENS (system notification service) that user has logged on.</p>
  
  <hr>
  
  <h2>Edit</h2>
  
  <p>On receiving SERVICE_CONTROL_SESSIONCHANGE / logon event I call WTSGetActiveConsoleSessionId() to get the current session then I use this session ID with WTSQueryUserToken() to get token.</p>
  
  <p>WTSGetActiveConsoleSessionId() sometimes returns me session 0. Thus I end up with token of session 0 when I want token from session of currently logged-in user.</p>
  
  <p>It depends on timing of WTSGetActiveConsoleSessionId() call.  </p>
  
  <p>By experimenting I came up with idea to wait for explorer.exe and only after it comes up call WTSGetActiveConsoleSessionId(), this seems to guarantee that I always get session 1 or above and thus corresponding token. </p>
  
  <p>Seeking a cleaner approach.</p>