Go to English page

ViaThinkSoft CodeLib

Dieser Artikel befindet sich in der Kategorie:
CodeLibProgrammierhilfenDelphi

{$IFDEF UNICODE}
function GetUserNameEx(NameFormat: DWORD; lpNameBuffer: LPWSTR; nSize: PULONG): DWORD;
          stdcall; external 'secur32.dll' Name 'GetUserNameExW';
{$ELSE}
function GetUserNameEx(NameFormat: DWORD; lpNameBuffer: LPSTR; nSize: PULONG): DWORD;
          stdcall; external 'secur32.dll' Name 'GetUserNameExA';
{$ENDIF}

function GetWindowsDisplayUserName: string;
const
  cnMaxUserNameLen = 254;
  EXTENDED_NAME_FORMAT_NameUnknown = 0;
  EXTENDED_NAME_FORMAT_NameFullyQualifiedDN = 1;
  EXTENDED_NAME_FORMAT_NameSamCompatible = 2;
  EXTENDED_NAME_FORMAT_NameDisplay = 3;
  EXTENDED_NAME_FORMAT_NameUniqueId = 6;
  EXTENDED_NAME_FORMAT_NameCanonical = 7;
  EXTENDED_NAME_FORMAT_NameUserPrincipal = 8;
  EXTENDED_NAME_FORMAT_NameCanonicalEx = 9;
  EXTENDED_NAME_FORMAT_NameServicePrincipal = 10;
  EXTENDED_NAME_FORMAT_NameDnsDomain = 12;
  EXTENDED_NAME_FORMAT_NameGivenName = 13;
  EXTENDED_NAME_FORMAT_NameSurname = 14;
var
  sUserName     : string;
  dwUserNameLen : DWord;
begin
  dwUserNameLen := cnMaxUserNameLen-1;
  SetLength( sUserName, cnMaxUserNameLen );
  if GetUserNameEx(
    EXTENDED_NAME_FORMAT_NameDisplay,
    PChar( sUserName ),
    @dwUserNameLen ) = 0 then
  begin
    Result := '';
    RaiseLastOsError;
  end;

  // There is probably a bug in Win10/Win11 in GetUserNameExW
  // When the attribute does not exist (e.g. the user has no display name),
  // then GetUserNameEx!=0 (success), but nSize stays untouched, not changed to 0!!!
  if dwUserNameLen = cnMaxUserNameLen-1 then dwUserNameLen := 0;

  SetLength( sUserName, dwUserNameLen );
  Result := sUserName;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(GetWindowsDisplayUserName);
end;
Daniel Marschall
ViaThinkSoft Mitbegründer