Changing the computer name with Inno Setup

2019-04-15 13:39发布

问题:

Is there a way to change your computer name with Inno Setup? I'm new to Inno Setup but I searched quite alot and I haven't found any example of it. I know you can access the computer name with the constant {computername}, but it seems like there is no function to change it.

I thought about changing the registry key of the computer name in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName with section [Registry], but I don't know what will happen if I use the syntax to create a new key. Will it overwrite it? Will it throw me an error? Any ideas would be appreciated.

Example of syntax for creating a new key

Root: HKLM; Subkey: "SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName"; ValueType: string; ValueName: "ComputerName"; ValueData: "MyNewComputerName";

回答1:

You should call SetComputerName API function.

Also as the computer name change is valid only after the computer restarts, you should set AlwaysRestart directive to yes to make the installer restart the computer after the installation.

[Setup]
AlwaysRestart=yes

[Code]

function SetComputerName(lpComputerName: PAnsiChar): BOOL;
    external 'SetComputerNameA@kernel32.dll stdcall';

procedure CurStepChanged(CurStep: TSetupStep);
begin
  if CurStep = ssInstall then
  begin
    Log('Changing computer name');
    if SetComputerName('MyNewName') then
    begin
      Log('Computer name changed');
    end
      else
    begin
      Log('Failed to change computer name - ' + SysErrorMessage(DLLGetLastError));
    end;
  end;
end;

Tested on Unicode version of Inno Setup.


Changing registry key might work too. Just you should use ComputerName key (not ActiveComputerName) and restart.

I believe your syntax is correct otherwise. Though I didn't test it. However note that maximal computer name length is 15 characters (so MyNewComputerName is too long).