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()
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
