Mega Code Archive

 
Categories / Delphi / Examples
 

Get the username and computer name from a computer

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;