如何在Windows中获得当前登录用户的域
How to get the domain of currently logged on user in Windows?
我知道我可以通过调用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:%sndomain:%sn"), user, domain);
}
}
在我的例子中输出:
user:dlaru_000
domain:IKH-WIN81
注意您必须将程序链接到advapi32.lib。
相关文章:
- 如何在 c++ 中将密码和用户名保存到 .txt 文件中.如果用户尝试登录,我仍然希望能够检索它们
- Win7 C++ - 从以用户身份登录的服务启动可执行文件的问题
- 用户注销/登录后,创建托盘图标时出现罕见错误
- 是否有任何 C 函数或 API 来获取当前登录用户下运行的进程列表
- 如何从 Windows 上的服务在未登录用户的桌面上启动应用程序
- 获取 Windows 系统已加入 Azure AD 时登录用户的 UserPrincipalName
- 加密用户数据,而不会丢失安卓应用程序中的登录用户
- 如何检查用户登录到Windows的时间
- 嗨,我正在尝试编码一个允许用户在Visual C 中登录的按钮,程序正在运行,但表单对话框未显示
- 如何从非管理员用户获取当前登录的用户名、域名和用户 sid
- 我如何将登录的用户登录到当前会话中的域用户
- 从 mfc 应用程序点击网络服务,并希望从网络服务登录方法读取用户代码返回
- 如何从另一个登录用户启动登录用户内部的应用程序
- 在多个登录用户系统中检索当前登录的用户 SID
- 如何获取当前登录用户的UPN(用户主体名称)
- 登录用户:程序意外完成
- 是否可以创建一个服务或应用程序,以编程方式在windows中登录用户
- 如何在Windows中获得当前登录用户的域
- 如何在 Windows 中获取登录用户的 SID
- 如果使用system用户令牌启动登录用户进程,是否会危及系统安全