winapicomputer-name

How to use SetComputerName from the windows api?


I'm trying to change the name of the computer programmatically. Occasionally we have to wipe a system and restore it's database in an upgrade. I'm trying to have all the system settings be read out of the database and be set up automatically. Most of it is pretty simple stuff, but changing the name of the system is really throwing me for a loop. EDIT: code edited to reflect changes from comments

if(dbHostName.length() > MAX_COMPUTERNAME_LENGTH)
{
    dbHostName.truncate(MAX_COMPUTERNAME_LENGTH);
}
LPCTSTR cname = dbHostName.toStdWString().c_str();
bool nameset = SetComputerNameEx(ComputerNamePhysicalDnsHostname, cname);
if(nameset) qDebug() << "Computer name changed to" << dbHostName;
else qDebug() << "Computer name NOT changed!";

I'm taking a QString in, making sure it's not too long, converting it to a standard wide string, converting that to a LPCTSTR and then attempting to use that to change the computer name.

This returns false: Computer name not changed!


Solution

  • Giving credit to @user4581301 and @IInspectable for contributing the suggestions that led to the the below solutions. Both of these worked, I chose the second one because there does not appear to be an agreement on how best to convert a string to an LPCTSTR object.

    if(dbHostName.length() > MAX_COMPUTERNAME_LENGTH)
    {
            dbHostName.truncate(MAX_COMPUTERNAME_LENGTH);
    }
    std::wstring wstring = dbHostName.toStdWString();
    LPCTSTR cname = wstring.c_str();
    SetComputerNameEx(ComputerNamePhysicalDnsHostname, cname);
    

    And this is the actual solution I selected, but again, they both worked on Windows 8.1.

    if(dbHostName.length() > MAX_COMPUTERNAME_LENGTH)
    {
            dbHostName.truncate(MAX_COMPUTERNAME_LENGTH);
    }
    std::string sname = dbHostName.toStdString();
    LPCSTR cname = sname.c_str();
    SetComputerNameExA(ComputerNamePhysicalDnsHostname, cname);
    

    Edit 5/24/18: Incidentally this also works, and is much more concise

    bool nameSet = SetComputerNameEx(ComputerNamePhysicalDnsHostname, dbHostName.toStdWString().c_str());