DelphiFAQ Home Search:

Get the username and computer name from a computer

 

commentsThis article has not been rated yet. After reading, feel free to leave comments and rate it.

For Win95, you can find it in the registry - but this is not portable to NT.

A safer way (and one which is portable to NT) would be to use the Win32 calls GetComputerName and GetUserName, both of which are defined in the Windows unit. Each of these functions takes a buffer as its first parameter and the length of the buffer as its second.

The function definitions are shown below:

function GetComputerName(lpBuffer: PChar; var nSize: DWORD): BOOL;
stdcall;
function GetUserName(lpBuffer: PChar; var nSize: DWORD): BOOL;
stdcall;

Thanks to Jonathan Arnett for a corrected version of previously posted code.

Use them like this:

function  GetWindowsUserName : string;
const
  cnMaxLen=254;
var
  dwUserNameLen : DWord;
begin
  dwUserNameLen:=cnMaxLen-1;
  SetLength(sUserName, cnMaxLen);

  GetUserName(@Result[1], dwUserNameLen);
  SetLength(Result, dwUserNameLen - {null term} 1 );
  if dwUserNameLen=cnMaxLen-1 then
    SetLength(Result,0);
end;
You don't like the formatting? Check out SourceCoder then!

Comments:

2006-07-03, 11:07:41
anonymous from United Kingdom  
However GetUserName does not work where impersonation is in use.

 

 

Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option.
 
It seems that you are
from Los Angeles, US .

Info/ Feedback on this

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:
photo Add a picture:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity. The owner of this web site reserves the right to delete such material.