简体   繁体   English

如何从Windows API使用SetComputerName?

[英]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. 我要插入一个QString,以确保它不太长,将其转换为标准的宽字符串,然后将其转换为LPCTSTR,然后尝试使用该字符串来更改计算机名称。

This returns false: Computer name not changed! 这将返回false:计算机名称未更改!

Giving credit to @user4581301 and @IInspectable for contributing the suggestions that led to the the below solutions. 感谢@ user4581301和@IInspectable贡献了导致以下解决方案的建议。 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. 这两种方法都有效,我选择了第二种方法,因为在如何最好地将字符串转换为LPCTSTR对象方面似乎尚未达成共识。

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. 这是我选择的实际解决方案,但同样,它们都可以在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 编辑5/24/18:顺便说一句,这也有效,并且更加简洁

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM