问题

如何在Firemoun Delphi项目中获取当前登录的用户名?我的目标是Windows和Mac.

我有XE2,但我想任何版本的解决方案都很好,因为如果需要,我将升级.

  最佳答案

对于 Windows,您可以使用 GetUserName WinAPI 函数,对于 OSX,您可以使用 NSUserName 和 /或 NSFullUserName 方法。

尝试OSX的这个示例

 {$APPTYPE CONSOLE}

{$R *.res}

uses
  Macapi.CoreFoundation,
  Macapi.Foundation,
  System.SysUtils;

function NSUserName: Pointer; cdecl; external '/System/Library/Frameworks/Foundation.framework/Foundation' name _PU +'NSUserName';
function NSFullUserName: Pointer; cdecl; external '/System/Library/Frameworks/Foundation.framework/Foundation' name _PU + 'NSFullUserName';

begin
  try
    Writeln(Format('User Name      %s',[TNSString.Wrap(NSUserName).UTF8String]));
    Writeln(Format('Full User Name %s',[TNSString.Wrap(NSFullUserName).UTF8String]))
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
 

对于Windows

 {$APPTYPE CONSOLE}


uses
  Windows,
  SysUtils;

function WUserName: String;
var
  nSize: DWord;
begin
 nSize := 1024;
 SetLength(Result, nSize);
 if GetUserName(PChar(Result), nSize) then
   SetLength(Result, nSize-1)
 else
   RaiseLastOSError;
end;


begin
  try
   Writeln(WUserName);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  readln;
end.
 

编译成一个单元:

 uses
  {$IFDEF MACOS}
  MacApi.CoreFoundation, MacApi.Foundation,
  {$ENDIF}
  {$IFDEF MSWINDOWS}
  Windows,
  {$ENDIF}
  System.SysUtils;

{$IFDEF MACOS}
function NSUserName: Pointer; cdecl; external '/System/Library/Frameworks/Foundation.framework/Foundation' name '_NSUserName';
{$ENDIF}

function GetUserName: String;
{$IFDEF MSWINDOWS}
var
  nSize: DWord;
{$ENDIF}
begin
  {$IFDEF MACOS}
  Result := TNSString.Wrap(NSUserName).UTF8String;
  {$ENDIF}
  {$IFDEF MSWINDOWS}
  nSize := 1024;
  SetLength(Result, nSize);
  if Windows.GetUserName(PChar(Result), nSize) then
  begin
    SetLength(Result, nSize - 1)
  end
  else
  begin
    RaiseLastOSError;
  end
  {$ENDIF}
end;
 

  相同标签的其他问题

delphifiremonkey