Delphi 对多个Windows版本和32/64使用GetUserName
是否可以通过Windows 8使用Windows XP的Win API函数GetUserName?对于32位和64位Delphi 对多个Windows版本和32/64使用GetUserName,delphi,winapi,Delphi,Winapi,是否可以通过Windows 8使用Windows XP的Win API函数GetUserName?对于32位和64位 function getUserName: String; var BufSize: DWord; Buffer: PWideChar; begin BufSize:= 1024; Buffer:= AllocMem(BufSize); try if GetUserName(Buffer, BufSize) then SetString(result
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;
答案是肯定的。GetUserName在所有Windows版本上都可用
但是,您显示的代码将仅在Delphi 2009及更高版本上编译,因为您将PWideChar传递给GetUserName和SetString,这仅在GetUserName映射到GetUserNameW且String映射到Unicode时才有效。如果需要在早期的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;
函数从Windows 2000一直到现在都可用,所以是的。您真的在问是/否问题吗?早期的Delphi版本不理解WinApi。Windows,最大用户名长度在lmcons.h JwaLmCons.pas中定义为UNLEN,值为256,以便用于缓冲区大小。使用UNLEN常量在将来不兼容。并不是说用户名有很多机会超过256个字符,但仍然如此。所以,我更喜欢使用不同的模式来处理Win32 API字符串函数。1调用GetUserName,缓冲区为零,缓冲区长度为零。2 get not Though buffer memory错误信号在不同的API函数中稍有不同,确切的所需长度也略有不同。3分配适当的内存,然后再次调用GetUserData获取真实数据。4不需要第二次调用SetLength,因为我们事先已经正确地调整了缓冲区的大小