您的功能是错误的,首先是:
function GetUserFromWindows: string;
var
iLen: Cardinal;
begin
iLen := 256; // UNLEN constant in LMCons.h says 256 - hard coded.
Result := StringOfChar(#0, iLen);
GetUserName(PChar(Result), iLen);
SetLength(Result, iLen);
end;
如果你真的想要计算机名称,正如你的问题标题所说,它并没有太大的不同:
function GetComputerNameFromWindows: string;
var
iLen: Cardinal;
begin
iLen := MAX_COMPUTERNAME_LENGTH + 1; // From Windows.pas
Result := StringOfChar(#0, iLen);
GetComputerName(PChar(Result), iLen);
SetLength(Result, iLen);
end;
现在你可以在任何你喜欢的地方使用它们中的任何一个:
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(GetUserFromWindows);
ShowMessage(GetComputerNameFromWindows);
end;
或者:
procedure TForm1.FormCreate(Sender: TObject);
begin
Label1.Caption := GetUserFromWindows;
Label2.Caption := GetComputerNameFromWindows;
end;