我使用此代码
如何将其作为信息显示在我的屏幕上?
Function GetUserFromWindows:String;
Var
UserName : string;
UserNameLen : Dword;
Begin
UserNameLen := 255;
SetLength(userName, UserNameLen) ;
If GetUserName(PChar(UserName), UserNameLen) Then
Result := Copy(UserName,1,UserNameLen - 1)
Else
Result := 'Unknown';
End;
答案 0 :(得分:12)
你的功能是错误的,首先是:
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;