C++ - GetUserName() when process is run as administrator(C++ - 以管理员身份运行进程时的 GetUserName())
问题描述
我有一个提示用户名的简单 C++ 程序
I have a simple C++ program that prompt the user name
#include <windows.h>
#include <Lmcons.h>
#include <winbase.h>
int _tmain(int argc, _TCHAR* argv[])
{
wchar_t username[UNLEN + 1];
DWORD username_len = UNLEN + 1;
::GetUserName(username, &username_len);
MessageBox(NULL, username, NULL, 1);
return 1;
}
GetUserName() 在管理员帐户中按预期执行,这意味着打印真实用户名.
GetUserName() performs as expected in administrator accounts, meaning print the real user name.
但是,当在非管理员帐户中以管理员身份运行时,我得到的是管理员名称,而不是真正的登录用户.
However, when run as administrator in a non-administrator account, I get the administrator name, and not the the real logged user.
我相信这种行为是意料之中的,因为它记录在 GetUserName():
如果当前线程正在模拟另一个客户端,GetUserName 函数会返回该线程正在模拟的客户端的用户名.
I believe this behavior is expected since it is documented in GetUserName():
If the current thread is impersonating another client, the GetUserName function returns the user name of the client that the thread is impersonating.
有没有办法获得真正的登录用户(非管理员用户),即使进程以管理员身份运行?
Is there a way to get the real logged in user (the non-admin one), even if the process run as administrator?
推荐答案
我相信你想问 Windows 的问题是哪个用户登录到当前会话".
I believe the question you want to ask Windows is "which user is logged into the current session".
为此,请调用 ProcessIdToSessionId() 用你自己的进程 ID 来确定当前的会话 ID.
To do this, call ProcessIdToSessionId() with your own process's ID to determine the current session ID.
然后调用 WTSQuerySessionInformation() 使用 WTSUserName
选项来获取用户名.
Then call WTSQuerySessionInformation() with the WTSUserName
option to fetch the user name.
这篇关于C++ - 以管理员身份运行进程时的 GetUserName()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ - 以管理员身份运行进程时的 GetUserName()


基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01