-1

GetUserNameWindowsXPからWindows8でWinAPI機能を使用することはできますか?32ビットと64ビットの両方で?

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;

ありがとう

4

1 に答える 1

4

答えはイエスです。 GetUserName()すべての Windows バージョンで使用できます。

ただし、示したコードはDelphi 2009 以降でのみコンパイルPWideCharGetUserName()れます。以前のバージョンの Delphi でコンパイルするコードが必要な場合は、代わりに, を使用して、実際に使用しているマッピングに一致させます。たとえば、次のようになります。SetString()GetUserName()GetUserNameW()StringUnicodeStringPCharPWideCharGetUserName()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;
于 2013-01-25T01:55:34.433 に答える