Question

Is it possible to use the Win API function GetUserName for Windows XP through Windows 8? For both 32 and 64 bit?

function getUserName: String;
var
  BufSize: DWord;
  Buffer: PWideChar;
begin
 BufSize:= 1024;
 Buffer:= AllocMem(BufSize);
 try
  if GetUserName(Buffer, BufSize) then
      SetString(result, Buffer, BufSize)
 else
  RaiseLastOSError;
 finally
  FreeMem(Buffer);
 end;
end;

thanx

Was it helpful?

Solution

The answer is yes. GetUserName() is available on all Windows versions.

However, the code you showed will only compile on Delphi 2009 and later, since you are passing a PWideChar to GetUserName() and SetString(), which only works if GetUserName() maps to GetUserNameW() and String maps to UnicodeString. If you need the code to compile on earlier Delphi versions, use PChar instead of PWideChar, to match whatever mapping GetUserName() and String are actually using, eg:

function getUserName: String;
const
  UNLEN = 256;
var
  BufSize: DWord;
  Buffer: PChar;
begin
  BufSize := UNLEN + 1;
  Buffer := StrAlloc(BufSize);
  try
    if Windows.GetUserName(Buffer, BufSize) then
      SetString(Result, Buffer, BufSize-1)
    else
      RaiseLastOSError;
  finally
    StrDispose(Buffer);
  end;
end;

Which can then be simplified to this:

function getUserName: String;
const
  UNLEN = 256;
var
  BufSize: DWord;
  Buffer: array[0..UNLEN] of Char;
begin
  BufSize := Length(Buffer);
  if Windows.GetUserName(Buffer, BufSize) then
    SetString(Result, Buffer, BufSize-1)
  else
    RaiseLastOSError;
end;

Or this:

function getUserName: String;
const
  UNLEN = 256;
var
  BufSize: DWord;
begin
  BufSize := UNLEN + 1;
  SetLength(Result, BufSize);
  if Windows.GetUserName(PChar(Result), BufSize) then
    SetLength(Result, BufSize-1)
  else
    RaiseLastOSError;
end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top