Home > Enterprise >  How to get Microsoft Windows 10/11 online account name using C /Qt6?
How to get Microsoft Windows 10/11 online account name using C /Qt6?

Time:10-17

The code, presumably, was working before, and returns empty string now.
Was something about NetUserGetInfo changed recently?

#include <windows.h>
#include <lmaccess.h>
#include <QLabel>
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString name;
    TCHAR  infoBuf[32767];
    DWORD  bufCharCount = 32767;
    LPUSER_INFO_0 pBuf = nullptr;

    GetUserName( infoBuf, &bufCharCount ); // infoBuf - local username
    NetUserGetInfo(nullptr,infoBuf,2, reinterpret_cast<LPBYTE*>(&pBuf));
    if (pBuf != nullptr)
    {
        LPUSER_INFO_2 pBuf2 = LPUSER_INFO_2(pBuf);
        name = QString::fromWCharArray( pBuf2->usri2_full_name );
    }
    qDebug() << "name: " << name;
    QLabel * label = new QLabel("|"   name   "|");
    label->show();

    return a.exec();
}

CodePudding user response:

Changes in API behaviors usually happen due to changes in security policies, unless documented otherwise. In that case, your initial assumptions about the API may have been wrong to begin with. As described in @SimonMourier's comment above.

Combining GetUserName with NetUserGetInfo is not 100% guaranteed. Read the remarks of both API, it very much depends on the current security setup, so it's possible it used to work for some reason and doesn't anymore for some reason. You should at least use GetUserNameEx to ensure a given format

That being said, you are using NetUserGetInfo() incorrectly. You are asking for level 2, so it will output a USER_INFO_2* pointer, not a USER_INFO_0* pointer that needs to be typecasted to USER_INFO_2*.

Try something more like this instead:

#include <windows.h>
#include <lmaccess.h>
#include <QLabel>
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString name;
    WCHAR userName[UNLEN 1];
    DWORD userNameCount = UNLEN 1;
    LPUSER_INFO_2 pBuf = nullptr;

    GetUserNameW( userName, &userNameCount ); // local username
    if (NetUserGetInfo(nullptr, userName, 2, reinterpret_cast<LPBYTE*>(&pBuf)) == NERR_Success && pBuf != nullptr)
    {
        name = QString::fromWCharArray( pBuf->usri2_full_name );
        NetApiBufferFree(pBuf);
    }

    qDebug() << "name: " << name;
    QLabel * label = new QLabel("|"   name   "|");
    label->show();

    return a.exec();
}

CodePudding user response:

GetUserName cannot react to Domain. NetUserGetInfo returns NERR_UserNotFound when the account is a domain account according to my test. You can use NetUserEnum to retrieve information about all user accounts on the local computer.

  • Related