delphi 修改电脑名称

发布时间 2023-09-19 22:25:11作者: 一曲轻扬

有多少人是因为SetComputerName无效之后找到这里的?请在评论区报一下名.

uses
  ShellAPI,windows;

procedure TForm1.ChangeComputerName(const NewName: string);
var
  Command: string;
  NewState: TTokenPrivileges;
  lpLuid: TLargeInteger;
  ReturnLength: DWORD;
  ToKenHandle: THANDLE;
begin
  //使用命令行来修改计算机名称
  Command :=
    '/C WMIC computersystem where name="%computername%" call rename name="' + NewName
    + '"';
  ShellExecute(0, 'open', 'cmd.exe', PChar(Command), nil, SW_HIDE);

  //提示是否重启电脑.需要提权操作
  if MessageDlg('计算机已被重新命名,需要重启计算机才能生效.是否现在重启?', mtInformation, [mbYes,
      mbNo], 0) = mrYes then
  begin
    OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY,
      ToKenHandle);

    if not LookupPrivilegeValue(nil, 'SeShutdownPrivilege', lpLuid) then
      RaiseLastOSError;

    NewState.PrivilegeCount := 1;
    NewState.Privileges[0].Luid := lpLuid;
    NewState.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;

    if not AdjustTokenPrivileges(ToKenHandle, False, NewState, SizeOf(NewState),
      nil, ReturnLength) then
      RaiseLastOSError;

    if not ExitWindowsEx(EWX_REBOOT, 0) then
      RaiseLastOSError;
  end;
end;