TechTricks
Technical answers from the trenches 
 
 
 
 

     
   
Obtaining the Computer Name
 
   
 Posted: 17 November 2000
 
   
 
 Applies to: Delphi 2.0 and later
 
       
   

Question: How do I get the computer name?

Use the getComputerName() function provided by the Windows API, as shown in the following code:

procedure TForm1.Button1Click(Sender: TObject);
var
   pcName : pchar;   // Holds the computer name
   dwSize : dword;   // Size of the buffer holding the name
begin

   try
      dwSize := MAX_COMPUTERNAME_LENGTH + 1;
      pcName := strAlloc( dwSize );

      if not getComputerName( pcName, dwSize ) then
         application.MessageBox(
            pChar( 'Reason: The API call failed' + #10#10 +
                   'Windows reports the error code as ' +
                   intToStr( getLastError ) ),
                   'Can''t Get Computer Name', ID_OK )
      else
         application.MessageBox(
            pChar( 'This computer is named "' + pcName +
                   '", which contains ' + intToStr( dwSize ) +
                   ' character(s).' ), 'FYI', ID_OK );
   finally
      strDispose( pcName );
   end;

end;

Please note that the above sample only uses basic error handling. Most API routines return values indicating success or failure. You should evaluate these return values and respond to error conditions. The specifics depend on the API function you're using. Use the Win32 Programmer's Reference Help file provided with Delphi to determine possible error conditions and recovery strategies.

You can use the getLastError() API function to obtain additional details about the error. As you might expect, the values it returns depends on the API function you're trying to work with.

While developing this example, we encountered the following errors. If you run into trouble with this routine, see if getLastError() reports one of the following values:

  • ERROR_INVALID_PARAMETER (Value: 87) indicates that dwSize doesn't report the number of characters actually allocated to pcName. According to the Windows API Help file, pcName needs to be have MAX_COMPUTERNAME_LENGTH + 1 characters in size. If getComputerName() fails and getLastError() reports 87, assign the length of pcName to dwSize before calling getComputerName().

  • ERROR_BUFFER_OVERFLOW (Value: 111) indicates that dwSize does not properly reflect the characters allocated for pcName. Use the same value for both (MAX_COMPUTERNAME_LENGTH + 1), as shown above.

For more information regarding getComputerName() or getLastError(), please consult the Win32 SDK Help file provided with Delphi.

 

       

Top

Feedback About Paradox Delphi Assorted Web Stuff
 
 
Copyright © 2000-2004, techtricks.com; All Rights Reserved.
Acknowledgements, Disclaimers, Terms and Conditions.
Article last updated on 31 May 2003

 

Other Sites: Paradox, Delphi, Perl, Web Stuff, and More


 

[- End -]