如何在Inno Setup中使用GetVolumeInformation?

时间:2012-02-14 05:48:57

标签: winapi installer inno-setup pascalscript

我需要在使用Inno Setup创建的安装过程中获取驱动器号的卷序列号。我知道DLL函数可以导入Inno,但我对它很新,并且在使它工作时遇到一些问题。我知道kernel32中的GetVolumeInformation函数可以做我需要的。有人可以告诉我如何在Inno脚本中导入和使用该功能来检索卷序列号吗?

谢谢!

2 个答案:

答案 0 :(得分:8)

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;

使用Inno-setup版本5.2.3进行测试 在Inno-Setup的Unicode版本中,将PChar替换为PAnsiChar

答案 1 :(得分:4)

由于InnoSetup不支持指针,因此您必须为GetVolumeInformation函数的调用创建外部库。以下代码示例应适用于Delphi和InnoSetup的所有组合(从Unicode支持的角度来看)。

这是Delphi库代码:

library VolumeInformation;

uses
  Types, Classes, SysUtils, Windows;

var
  SerialNumber: AnsiString;

function GetVolumeSerial(Drive: PAnsiChar): PAnsiChar; stdcall;
var
  FileSystemFlags: DWORD;
  VolumeSerialNumber: DWORD;
  MaximumComponentLength: DWORD;
begin
  SerialNumber := '';
  GetVolumeInformationA(Drive, nil, 0, @VolumeSerialNumber,
    MaximumComponentLength, FileSystemFlags, nil, 0);
  SerialNumber := IntToHex(HiWord(VolumeSerialNumber), 4) + ' - ' +
    IntToHex(LoWord(VolumeSerialNumber), 4);
  Result := PAnsiChar(SerialNumber);
end;

exports
  GetVolumeSerial;

end.

这是InnoSetup代码:

[Files]
Source: "VolumeInformation.dll"; Flags: dontcopy

[Code]

function GetVolumeSerial(Drive: PAnsiChar): PAnsiChar;
  external 'GetVolumeSerial@files:VolumeInformation.dll stdcall setuponly';

procedure ButtonOnClick(Sender: TObject);
var
  S: string;
begin
  S := GetVolumeSerial('c:\');
  MsgBox(S, mbInformation, mb_Ok);
end;