Wednesday, June 25, 2008

DELPHI TRICK - GETTING THE VOLUME SERIAL NUMBER

When a disk/diskette is formatted, Windows stores a serial number in the
boot sector. This number is calculated using the system time and is not
guaranteed to be unique, but it is quite unlikely that two disks taken
at random have the same serial number.

You can use this number for a copy protection mechanism, to insure an
application can only be run from the hard disk where you originally
installed it. For example you can store the serial number in the Windows
Registry and compare it with the disk serial number every time the
application starts. We leave this part up to you.

To obtain the serial number you have to call the GetVolumeInformation
API function declared in the Windows unit. Notice you can also call
this function to obtain the volume label, the maximum length of a
filename, the file system type (for example 'FAT32') and the file system
options (like disk/file compression and case sensitivity and character
set of file names).

The following function is a wrapper for the GetVolumeInformation API and
returns the serial number of the drive passed as parameter:

function GetVolumeSerialNumber(const drive: TFilename): longword;
var
VolumeName, FileSystemName: array[0..MAX_PATH-1] of char;
VolumeSerialNumber, MaxFilenameLength, FileSystemFlags: longword;
begin
GetVolumeInformation(PChar(IncludeTrailingBackslash(drive)),
VolumeName, MAX_PATH, @VolumeSerialNumber, MaxFilenameLength,
FileSystemFlags, FileSystemName, MAX_PATH);
Result := VolumeSerialNumber;
end;

Sample call:

procedure TForm1.Button1Click(Sender: TObject);
var
serial: longword;
begin
serial := GetVolumeSerialNumber('C:\');
ShowMessage(IntToHex(HiWord(serial), 4)
+ '-' + IntToHex(LoWord(serial), 4));
end;

No comments: