unit hddserial;

interface

type
  DWORD = LongWord;

function HardDiskSerial( const Drive: PChar ): DWORD;

function SetErrorMode(uMode: LongWord): LongWord; external 'SetErrorMode@kernel32.dll stdcall'; 
function GetVolumeInformation(lpRootPathName: PChar;
  lpVolumeNameBuffer: PChar; nVolumeNameSize: DWORD; var lpVolumeSerialNumber: DWORD;
  var lpMaximumComponentLength, lpFileSystemFlags: DWORD;
  lpFileSystemNameBuffer: PChar; nFileSystemNameSize: DWORD): boolean;  external 'GetVolumeInformationA@kernel32.dll stdcall'; 

const 
  SEM_FAILCRITICALERRORS = 1;

implementation

{Returns the serial number of the specified disk.}
{Returns 0 if the disk is not valid or has no serial number. The Drive parameter
must either be the name of a local drive (e.g. C:\) or network share
(e.g. \\MyServer\MyShare\). A trailing backslash must be provided.
A drive letter on its own will not be recognised.}
function HardDiskSerial( const Drive: PChar ): DWORD;
var
  Unused: DWord; // unused parameters
  PrevErrorMode: LongWord; // stores Windows error mode
  nothing: pchar;
begin
  // Inhibit system dialog appearing on error
  PrevErrorMode := SetErrorMode(SEM_FAILCRITICALERRORS);
  nothing:='';
  try
    Result := 0;
    if not GetVolumeInformation(Drive, nothing, 0, Result, Unused, Unused, nothing, 0) then
      result:=0;
  finally
    // Restore old error mode
    SetErrorMode( PrevErrorMode );
  end;
end;

end.