Help & Manual authoring tool
How to get the user name of a Windows session?

Getting the user name of a Windows session

Copyright © 2000 Ernesto De Spirito

Pascal Newsletter. Free ezine for Delphi (and Kylix) programmers with articles, news, reviews, tips, trinks, and links to new Delphi content on the web!

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
Copyright © 2000/2006 Ernesto De Spirito.   All rights reserved.