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()
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
