Delphi - GetUserNameEx

(*
 * Author  : http://www.michael-puff.de
 * Date    : 2006-03-29
 * License : PUBLIC DOMAIN
 *)

function GetUserNameEx(NameFormat: DWORD; lpNameBuffer: LPSTR; var nSize: DWORD): Boolean; stdcall; external
  'secur32.dll' Name 'GetUserNameExA';

function GetLoggedOnUserNameEx(fFormat: DWORD; var Username: string): DWORD;

const
  NameUnknown       = 0; // Unknown name type.
  NameFullyQualifiedDN = 1; // Fully qualified distinguished name
  NameSamCompatible = 2; // Windows NT® 4.0 account name
  NameDisplay       = 3; // A "friendly" display name
  NameUniqueId      = 6; // GUID string that the IIDFromString function returns
  NameCanonical     = 7; // Complete canonical name
  NameUserPrincipal = 8; // User principal name
  NameCanonicalEx   = 9;
  NameServicePrincipal = 10; // Generalized service principal name
  DNSDomainName     = 11; // DNS domain name, plus the user name

var
  Size              : DWORD;
  Buffer            : array[0..1024] of Char;
begin
  Result := 0;
  Size := sizeof(Buffer);
  if GetUserNameEx(fFormat, Buffer, Size) then
    SetString(Username, Buffer, Size)
  else
    Result := GetLastError;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Username          : string;
  err               : DWORD;
begin
  err := GetLoggedOnUserNameEx(3, Username);
  if err = 0 then
    ShowMessage(Username)
  else
    ShowMessage(SysErrorMessage(err));
end;

2012-01-26T23:14:40 +0100, mail[at]michael-puff.de