How to get the user name of a Windows session?

Getting the user name of a Windows session

Copyright © 2000 Ernesto De Spirito

LMD-Tools 6.1 - 300+ components for various development tasks!

GetUserName

If we need to know the name with which the user of the system has logged in to start his Windows session, we can use the Windows API function GetUserName. The next function encapsulates the call to this API to return the user name as a string.

uses Windows;

function GetLoginName: string;
var
  buffer: array[0..255] of char;
  size: dword;
begin
  size := 256;
  if GetUserName(buffer, size) then
    Result := buffer
  else
    Result := ''
end;

Sample call

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage(GetLoginName);
end;
JfControls Library - for Delphi and C++ Builder