Mirror

Retrieve the computer name (Views: 300)


Problem/Question/Abstract:

How to retrieve the computer name

Answer:

Solve 1:

function ComputerName: string;
var
  size: DWORD;
begin
  size := MAX_COMPUTERNAME_LENGTH + 1;
  SetLength(Result, size - 1);
  if not GetComputerName(PChar(Result), size) then
    Result := '';
end;


Solve 2:

uses
  Windows;

procedure GetPCName(var PCName: string);
var
  nSize: DWORD;
begin
  nSize := MAX_COMPUTERNAME_LENGTH + 1;
  PCName := '';
  SetLength(PCName, nSize);
  if GetComputerName(PChar(PCName), nSize) then
    SetLength(PCName, nSize);
end;


Solve 3:

function GetLocalComputerName: string;
var
  iLen: cardinal;
begin
  iLen := 255;
  SetLength(Result, iLen + 1);
  if (GetComputerName(PChar(Result), iLen) = false) then
  begin
    RaiseLastWin32Error;
  end;
  SetLength(Result, iLen);
end;

<< Back to main page