How to get currently logged in username?

Marcus Adams picture Marcus Adams · Jul 11, 2013 · Viewed 21.8k times · Source

How do you get the currently logged in username in a Firemonkey Delphi project? I'm targeting both Windows and Mac.

I have XE2, but I suppose any version solution is fine because I will upgrade if needed.

Answer

RRUZ picture RRUZ · Jul 11, 2013

For Windows you can use the GetUserName WinAPi function, for OSX you can use the NSUserName and/or NSFullUserName methods.

Try this sample for 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.

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

Compiled into a single unit:

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;