Главная страница | назад





Article #15597: Retrieving a users login name.

 Question and Answer Database

FAQ597D.txt   Retrieving a users login name.
Category   :Windows API
Platform    :All
Product    :All 32 bit  

Question:
How do I get the user's login name under 32-bit versions of
Windows?


Answer:
The following function demonstrates how to use the GetUserName API call to accomplish this task in Delphi 3 or higher:
 
function GetCurrentUserName: string;
var
  Len: Cardinal; { This will have to be Integer, not cardinal, in Delphi 3. }
begin
  Len := 255;  { arbitrary length to allocate for username string, plus one for null terminator }
  SetLength(Result, Len - 1); { set the length }
  if GetUserName(PChar(Result), Len) then  { get the username }
    SetLength(Result, Len - 1) { set the exact length if it succeeded }
  else
  begin
    RaiseLastWin32Error; { raise exception if it failed }
  end;
end;


In Delphi 2, use a function like the following:

function GetCurrentUserName2: string;
var
  Len: integer;
  buf: array [0..255] of char;
begin
  Len := SizeOf(buf);
  if GetUserName(@buf,Len) then
  begin
    Result := buf;
  end
  else
  begin
    Raise Exception.Create('Win32 Error: ' + IntToStr(GetLastError)); { You could use FormatMessage to translate the error code into an error message } 
  end;
end;


01/06/00
 

Last Modified: 06-JAN-00