答案是肯定的。 GetUserName()适用于所有 Windows 版本。
但是,您显示的代码只能在 Delphi 2009 及更高版本上编译,因为您正在传递一个PWideChartoGetUserName()和SetString(),它仅在GetUserName()映射到GetUserNameW()和String映射到时才有效UnicodeString。如果您需要在早期的 Delphi 版本上编译代码,请使用PChar而不是PWideChar, 来匹配任何映射GetUserName()并String实际使用,例如:
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;
然后可以简化为:
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;
或这个:
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;