我知道我可以通过调用 GetUserName 来获取当前登录的用户名。我正在寻找一个返回该用户域的 API 函数。
请参阅 如何在 Windows NT、Windows 2000 或 Windows XP 上检索当前用户和域名。
示例:
#define UNICODE
#define _UNICODE
#include <windows.h>
#include <tchar.h>
BOOL GetCurrentUserAndDomain(PTSTR szUser, PDWORD pcchUser,
PTSTR szDomain, PDWORD pcchDomain) {
BOOL fSuccess = FALSE;
HANDLE hToken = NULL;
PTOKEN_USER ptiUser = NULL;
DWORD cbti = 0;
SID_NAME_USE snu;
__try {
// Get the calling thread's access token.
if (!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE,
&hToken)) {
if (GetLastError() != ERROR_NO_TOKEN)
__leave;
// Retry against process token if no thread token exists.
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY,
&hToken))
__leave;
}
// Obtain the size of the user information in the token.
if (GetTokenInformation(hToken, TokenUser, NULL, 0, &cbti)) {
// Call should have failed due to zero-length buffer.
__leave;
} else {
// Call should have failed due to zero-length buffer.
if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
__leave;
}
// Allocate buffer for user information in the token.
ptiUser = (PTOKEN_USER) HeapAlloc(GetProcessHeap(), 0, cbti);
if (!ptiUser)
__leave;
// Retrieve the user information from the token.
if (!GetTokenInformation(hToken, TokenUser, ptiUser, cbti, &cbti))
__leave;
// Retrieve user name and domain name based on user's SID.
if (!LookupAccountSid(NULL, ptiUser->User.Sid, szUser, pcchUser,
szDomain, pcchDomain, &snu))
__leave;
fSuccess = TRUE;
} __finally {
// Free resources.
if (hToken)
CloseHandle(hToken);
if (ptiUser)
HeapFree(GetProcessHeap(), 0, ptiUser);
}
return fSuccess;
}
int main()
{
TCHAR user[1024], domain[1024];
DWORD chUser = sizeof(user), chDomain = sizeof(domain);
if (GetCurrentUserAndDomain(user, &chUser, domain, &chDomain))
{
_tprintf(TEXT("user:%s\ndomain:%s\n"), user, domain);
}
}
我的例子的输出:
user:dlaru_000
domain:IKH-WIN81
请注意,您必须将程序链接到 advapi32.lib。
另一种可能,似乎涉及更少的代码,是调用 GetUserNameEx 并将
NameFormat
参数设置为 NameSamCompatible
,然后从输出字符串的开头提取一个子字符串(但不包括)第一个 \
字符。如果当前用户使用非域帐户登录,则子字符串将是计算机名称。 (如果输出字符串不包含 \
字符,则域名必然为空。)