Win API GetUserName返回SYSTEM

Rat*_*hma 0 c++ service winapi

我有这个方法来获取当前登录用户的用户名,当我将我的应用程序作为控制台应用程序运行时它工作正常,但是当我将它作为Windows服务运行时,它给我SYSTEM作为用户名!即使我将我的应用程序作为Windows服务运行,任何想法都能实现我想要的行为?

bool GetCurrentUserName(std::wstring& userName)
{
    const int INFO_BUFFER_SIZE = 32767;
    TCHAR infoBuf[INFO_BUFFER_SIZE] = L"";
    DWORD bufCharCount = INFO_BUFFER_SIZE;

    if (GetUserName(infoBuf, &bufCharCount))
    {
        userName = std::wstring(infoBuf);
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

MSa*_*ers 5

由于可以有0个,1个或更多用户登录,因此您需要LsaEnumerateLogonSessions.对于每个用户,请致电LsaGetLogonSessionData以获取用户名.