Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best method for getting the local computer name in Delphi

The code needs to be compatible with D2007 and D2009.


My Answer: Thanks to everyone who answered, I've gone with:

function ComputerName : String;
var
  buffer: array[0..255] of char;
  size: dword;
begin
  size := 256;
  if GetComputerName(buffer, size) then
    Result := buffer
  else
    Result := ''
end;
like image 412
Alister Avatar asked Jul 20 '09 23:07

Alister


3 Answers

The Windows API GetComputerName should work. It is defined in windows.pas.

like image 100
Mark Wilkins Avatar answered Oct 06 '22 18:10

Mark Wilkins


Another approach, which works well is to get the computer name via the environment variable. The advantage of this approach (or disadvantage depending on your software) is that you can trick the program into running as a different machine easily.

Result := GetEnvironmentVariable('COMPUTERNAME');

The computer name environment variable is set by the system. To "override" the behavior, you can create a batch file that calls your program, setting the environment variable prior to the call (each command interpreter gets its own "copy" of the environment, and changes are local to that session or any children launched from that session).

like image 25
skamradt Avatar answered Oct 06 '22 18:10

skamradt


GetComputerName from the Windows API is the way to go. Here's a wrapper for it.

function GetLocalComputerName : string;
    var c1    : dword;
    arrCh : array [0..MAX_PATH] of char;
begin
  c1 := MAX_PATH;
  GetComputerName(arrCh, c1);
  if c1 > 0 then
    result := arrCh
  else
    result := '';
end;
like image 38
3 revs, 3 users 93% Avatar answered Oct 06 '22 18:10

3 revs, 3 users 93%