16

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

我有 XE2,但我想任何版本的解决方案都可以,因为如果需要我会升级。

4

3 回答 3

28

对于 Windows,您可以使用GetUserNameWinAPi 函数,对于 OSX,您可以使用NSUserNameand/orNSFullUserName方法。

试试这个 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;
于 2013-07-11T17:27:47.157 回答
13

另一个更简单的解决方案是使用GetEnvironmentVariable函数通过环境变量获取计算机名称,如下所示:

Result := GetEnvironmentVariable('USERNAME');

PS此解决方案适用于 Windows 和 Linux,但您需要检查您的 Delphi 源代码是否受支持。

于 2017-03-11T08:16:07.007 回答
2

Windows 用户的简单答案

function CurrentUserName:String;  
var  
  UserName: array[0..127] of Char;  
  Size:DWord;  
begin  
  Size:=SizeOf(UserName);  
  GetUserName(UserName,Size);  
  Result:=UserName;  
end;  

来自edn

于 2021-03-17T11:23:56.593 回答