Generally use the GetUserName (or GetUserNameEx) function to get the current login login username (but not always, the following analysis), this system function in the Win95, WinNT and later all operating systems are available. The code is as follows:
BOOL CSecurityTool::GetCurrProcessUser(CString& strName)
{
BOOL bRet(TRUE);
strName = _T("");
DWORD dwSize = MAX_PATH;
TCHAR *pszName = new TCHAR[dwSize];
if (!GetUserName(pszName, &dwSize))
{
delete[] pszName;
pszName = new TCHAR[dwSize];
bRet = GetUserName(pszName, &dwSize);
}
strName = pszName;
delete[] pszName;
return bRet;
}
The exact number of this letter is the user name of the current thread (MSDN: Retrieves the "user name"). If the NT service (NT Server) starts this process, the result is the user name of the NT service process, that is, "SYSTEM" rather than the login username; Similarly, if this process was created through CreateProcessAsUser, The user that GetUserName gets will be the user name of "Asuser". In addition, if the current line one thread impersonate other user environments (which can be achieved with a function impersonateloggedonuser), it gets the other user names. Therefore, this function can only get the login username in a specific environment.
How do you get the login username exactly because the process itself is different from the operating environment?
Let's take a look at the Windows XP operating system, which provides a wtsquerysessioninformation function that gets information about sessions (session), one of which is to get the login user for the session. The code is as follows:
BOOL CSecurityTool::GetLogUserXP(CString& strName)
{
BOOL bRet = FALSE;
strName = _T("");
//for xp or above
TCHAR *szLogName = NULL;
DWORD dwSize = 0;
if (WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE,
WTS_CURRENT_SESSION,
WTSUserName,
&szLogName,
&dwSize))
{
strName = szLogName;
WTSFreeMemory(szLogName);
bRet = TRUE;
}
return bRet;
}