C++ - 以管理员身份运行进程时的 GetUserName() [英] C++ - GetUserName() when process is run as administrator

查看:69
本文介绍了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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆