한 걸음씩..

GetLogOnUserName 본문

프로그래밍

GetLogOnUserName

반엘 2014. 7. 14. 13:04

/************************************

*    3단계 User Name 얻어오는 방법 

*    GetUserName API를 통해 얻어오는 

*    방법과 환경변수를 참조하여 얻어오는 방법

*    두 가지를 사용하였으나 최근 System 권한으로

*    실행 시 User Name을 SYSTEM으로 얻어오는

*    오류를 발견하여 WTSQuerySessionInformation 

*    API를 통해 얻어오는 방법 추가

************************************/





#include <WtsApi32.h>

#pragma comment( lib, "Wtsapi32.lib" )


bool GetLogOnUserName( TCHAR * pOutUserName )

{

DWORD Size = UNLEN * 2;

LPTSTR pStr = NULL;

size_t requiredSize;

/*************************************************************

* Step. 1

* GetUserName API를 통해 얻어온다.

* 2014. 08. 22 JeonSB

*************************************************************/

BOOL bUserName = GetUserName( pOutUserName, &Size );

if( bUserName && *pOutUserName != NULL )

{

if( CString( pOutUserName ).CompareNoCase( _T("SYSTEM") ) == 0 )

{

ZeroMemory( pOutUserName, UNLEN * 2 );

/*************************************************************

* Step. 2

* WTSQuerySessionInformation API 통해 얻어온다.

*         2014. 08. 22 JeonSB

*************************************************************/

Size = 0;

WTSQuerySessionInformation( WTS_CURRENT_SERVER_HANDLE,

       WTS_CURRENT_SESSION, 

 WTSUserName, 

 &pStr, 

 &Size );


wcscpy( pOutUserName, pStr );

if( *pOutUserName != NULL )

     return true;

}


return true;

}


/*************************************************************

* Step. 3

* 환경변수를 통해 얻어온다.

* 2014. 08. 22 JeonSB

*************************************************************/

_tgetenv_s( &requiredSize, NULL, 0, _T("USERNAME") );

_tgetenv_s( &requiredSize, pOutUserName, requiredSize, _T("USERNAME") );

if( *pOutUserName != NULL )

          return true;


  MessageBox( _T("Get User Name is Fail") );


return false;

}