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

依然范特西╮ 提交于 2019-12-22 05:59:27

问题


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;

回答1:


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




回答2:


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).




回答3:


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;



回答4:


What about this :

function GetComputerName: string;
var
  buffer: array[0..MAX_COMPUTERNAME_LENGTH + 1] of Char;
  Size: Cardinal;
begin
  Size := MAX_COMPUTERNAME_LENGTH + 1;
  Windows.GetComputerName(@buffer, Size);
  Result := StrPas(buffer);<br/>
end;

From http://exampledelphi.com/delphi.php/tips-and-tricks/delphi-how-to-get-computer-name/




回答5:


I use this,

function GetLocalPCName: String;
var
    Buffer: array [0..63] of AnsiChar;
    i: Integer;
    GInitData: TWSADATA;
begin
    Result := '';
    WSAStartup($101, GInitData);
    GetHostName(Buffer, SizeOf(Buffer));
    Result:=Buffer;
    WSACleanup;
end;

Bye



来源:https://stackoverflow.com/questions/1156544/whats-the-best-method-for-getting-the-local-computer-name-in-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!