C++ - 以管理员身份运行进程时的 GetUserName()

2022-01-18 00:00:00 windows-vista windows-7 windows-xp c++

我有一个提示用户名的简单 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.

相关文章