简体   繁体   English

如何获取Windows中当前登录用户的域?

[英]How to get the domain of currently logged on user in Windows?

I know I can get the currently logged on user name by calling GetUserName . 我知道我可以通过调用GetUserName获得当前登录的用户名。 I'm looking for an API function that returns the domain of this user. 我正在寻找返回该用户域的API函数。

See How to retrieve current user and domain names on Windows NT, Windows 2000, or Windows XP . 请参阅如何在Windows NT,Windows 2000或Windows XP上检索当前的用户名和域名

Example: 例:

#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);
    }
}

Output in my case: 在我的情况下输出:

user:dlaru_000
domain:IKH-WIN81

Notice that you must link the program against advapi32.lib. 请注意,您必须将程序链接到advapi32.lib。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM