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

查看:228
本文介绍了C ++ - 当进程以管理员身份运行时的GetUserName()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的C ++程序提示用户名

  #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()在管理员帐户中执行,意味着打印真实的用户名。 p>

但是,以管理员身份在非管理员帐户中运行时,我会获得管理员名称,而不是真正记录的用户。



我相信这种行为是预期的,因为它记录在 GetUserName()

如果当前线程正在模拟另一个客户端,GetUserName函数返回线程模拟的客户端的用户名。



问题



解决方案

是一种获取真正登录用户(非管理员)我相信您要问Windows的问题是哪个用户登录到当前会话。



要执行此操作,请调用 ProcessIdToSessionId()与您自己的进程ID,以确定当前会话ID。



然后调用 WTSQuerySessionInformation()使用 WTSUserName 选项获取用户名。


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() 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.

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.

Question

Is there a way to get the real logged in user (the non-admin one), even if the process run as administrator?

解决方案

I believe the question you want to ask Windows is "which user is logged into the current session".

To do this, call ProcessIdToSessionId() with your own process's ID to determine the current session ID.

Then call WTSQuerySessionInformation() with the WTSUserName option to fetch the user name.

这篇关于C ++ - 当进程以管理员身份运行时的GetUserName()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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