/*
 * An example of how to use WTSQuerySessionInformation to get the logged on user UPN
 *
 * Copyright (c) 2009 Mounir IDRASSI <mounir.idrassi@idrix.fr>. All rights reserved.
 *
 * This program is distributed in the hope that it will be useful, 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 * or FITNESS FOR A PARTICULAR PURPOSE.
 * 
 */


#ifndef _WIN32_WINNT		      // Allow use of features specific to Windows X or later.                   
#define _WIN32_WINNT 0x0501	// Change this to the appropriate value to target other versions of Windows.
#endif	

#include <windows.h>
#include <WtsApi32.h>
#include <tchar.h>


#pragma comment(lib, "WtsApi32.lib")




int _tmain(int argc, TCHAR** argv)
{
   LPTSTR szUserName = NULL;
   LPTSTR szDomainName = NULL;
   DWORD dwLen = 0;
   BOOL bStatus = WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE,
                     WTS_CURRENT_SESSION,
                     WTSDomainName,
                     &szDomainName,
                     &dwLen);
   if (bStatus)
   {
      bStatus = WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE,
                     WTS_CURRENT_SESSION,
                     WTSUserName,
                     &szUserName,
                     &dwLen);
      if (bStatus)
      {
         DWORD cbUpn = _tcslen(szUserName) + 1 + _tcslen(szDomainName);
         LPTSTR szUpn = (LPTSTR) LocalAlloc(0, (cbUpn + 1) * sizeof(TCHAR));

         _tcscpy(szUpn, szUserName);
         _tcscat(szUpn, _T("@"));
         _tcscat(szUpn, szDomainName);

         _tprintf(_T("UPN = %s\n"), szUpn);

         LocalFree(szUpn);
         WTSFreeMemory(szUserName);
      }
      else
      {
         _tprintf(_T("WTSQuerySessionInformation on WTSUserName failed with error 0x%.8X\n"), GetLastError());
      }
      WTSFreeMemory(szDomainName);
   }
   else
   {
      _tprintf(_T("WTSQuerySessionInformation on WTSDomainName failed with error 0x%.8X\n"), GetLastError());
   }
   return 0;
}
