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;