I have used GetUserName() METHOD , but the username it returned is 'SYSTEM' in a SYSTEM process.How can I get the active username in a SYSTEM process? THIS IS MY CODE:
void getComputerUsername(char * username,char * domainname)
{
HANDLE hp , htoken;
char buff[1024];
unsigned long size = 1024;
TOKEN_USER *tuser;
PSID sid;
TCHAR * user = new TCHAR[256];
TCHAR * domain=new TCHAR[256];
SID_NAME_USE snu;
hp = htoken = INVALID_HANDLE_VALUE;
hp = GetCurrentProcess();
if(OpenProcessToken(hp, TOKEN_QUERY, &htoken))
{
if(GetTokenInformation(htoken, TokenUser, (void*)buff, size, &size))
{
tuser = (TOKEN_USER*)buff;
sid = tuser->User.Sid;
size = 256;
if(LookupAccountSid(NULL, sid, user, &size, domain, &size, &snu))
{
int iLength = WideCharToMultiByte(CP_ACP, 0, user, -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_ACP, 0, user, -1, username, iLength, NULL, NULL);
iLength = WideCharToMultiByte(CP_ACP, 0, domain, -1, NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_ACP, 0, domain, -1, domainname, iLength, NULL, NULL);
//strcpy( user,username);
}
}
}
}
If you want to know who is logged onto the physical console, you can call WTSGetActiveConsoleSessionId
to get the terminal services (aka "fast user switching" aka "remote desktop") session ID that is currently active.
You can then call WTSQuerySessionInformation
with WTSUserName
to get the username.
(If the user you're interested in might be logged on via Remote Desktop, this approach will not work.)