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
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
PWideChartoGetUserName()andSetString(), which only works ifGetUserName()maps toGetUserNameW()andStringmaps toUnicodeString. If you need the code to compile on earlier Delphi versions, usePCharinstead ofPWideChar, to match whatever mappingGetUserName()andStringare actually using, eg:Which can then be simplified to this:
Or this: