Search code examples
winapiinstallationinno-setuppascalscript

How can I use GetVolumeInformation in Inno Setup?


I need to get the volume serial number for a drive letter during an installation created with Inno Setup. I know that DLL functions can be imported into Inno, but I'm fairly new to it and having some problems getting it to work. I know that the GetVolumeInformation function in kernel32 can do what I need. Could someone show me how to import and use that functionality in an Inno script to retrieve the volume serial number?

Thanks!


Solution

  • Inno-Setup code::

    [Code]
    function GetVolumeInformation(
      lpRootPathName: PChar;
      lpVolumeNameBuffer: PChar;
      nVolumeNameSize: DWORD;
      var lpVolumeSerialNumber: DWORD;
      var lpMaximumComponentLength: DWORD;
      var lpFileSystemFlags: DWORD;
      lpFileSystemNameBuffer: PChar;
      nFileSystemNameSize: DWORD
      ): BOOL;
      external 'GetVolumeInformationA@kernel32.dll stdcall';
    
    
    function LoWord(dw: DWORD): WORD;
    begin
      Result := WORD(dw);
    end;
    
    function HiWord(dw: DWORD): WORD;
    begin
      Result := WORD((dw shr 16) and $FFFF);
    end;
    
    function WordToHex(w: WORD): string;
    begin
      Result := Format('%.4x', [w]);
    end;
    
    function FindVolumeSerial(const Drive: string): string;
    var
      FileSystemFlags: DWORD;
      VolumeSerialNumber: DWORD;
      MaximumComponentLength: DWORD;
    begin
      Result := '';
      // Note on passing PChars using RemObjects Pascal Script:
      // '' pass a nil PChar  
      // #0 pass an empty PChar    
      if GetVolumeInformation(
        PChar(Drive), 
        '', // nil
        0,
        VolumeSerialNumber,
        MaximumComponentLength,
        FileSystemFlags,
        '', // nil
        0)
      then
        Result := WordToHex(HiWord(VolumeSerialNumber)) + '-' + WordToHex(LoWord(VolumeSerialNumber));
    end;
    
    function InitializeSetup(): Boolean;
    begin
      MsgBox(FindVolumeSerial('c:\'), mbInformation, mb_Ok);
    end;
    

    Tested with Inno-setup version 5.2.3
    In Unicode versions of Inno-Setup replace PChar with PAnsiChar