Inno Setup How to edit a ini file during the insta

2019-07-20 07:18发布

问题:

I am making an installer that needs to edit an INI file during the installation. In this case I need to edit only two keys from that ini file.

These two:

filename: rev.ini; Section: Emulator; Key: Language; 
filename: rev.ini; Section: steamclient; Key: PlayerName;

I Want The installer to give me the option to select the laguage or use the default language that I already selected from the start in the lenguage menu, and for the PlayerName. Give the option to write any name i want. I didnt see anything like this. only read or put established values in inifiles.

this is my code:

; Script generated by the Inno Setup Script Wizard.
; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!
#include "botva2.iss"
#include "BASS_Module.iss"
#define MyAppName "XXX"
#define MyAppVersion "XXX"
#define MyAppPublisher "XXX"
#define MyAppURL "example.com"


[Setup]
; NOTE: The value of AppId uniquely identifies this application.
; Do not use the same AppId value in installers for other applications.
; (To generate a new GUID, click Tools | Generate GUID inside the IDE.)
AppID={{AA8DB34C-8DE2-468C-8A3A-0DADD1A9C38E}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
;AppVerName={#MyAppName} {#MyAppVersion}
AppPublisher={#MyAppPublisher}
AppPublisherURL={#MyAppURL}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName={pf}\
DefaultGroupName={#MyAppName}
LicenseFile=Log1.rtf
InfoBeforeFile=Log2.rtf
InfoAfterFile=Log3.rtf
OutputDir=Output Installer\
OutputBaseFilename=XXX 2xxx-2xxx
SetupIconFile=xxx.ico
Compression=lzma2/Ultra64
SolidCompression=true
InternalCompressLevel=Ultra64
Uninstallable=false
WizardImageFile=fondosetup.bmp
WizardSmallImageFile=0.bmp
CreateAppDir=true
UsePreviousAppDir=true
DirExistsWarning=no
AllowCancelDuringInstall=false


[Languages]
Name: "default"; MessagesFile: "compiler:Default.isl"
Name: "catalan"; MessagesFile: "compiler:Languages\Catalan.isl"
Name: "french"; MessagesFile: "compiler:Languages\French.isl"
Name: "german"; MessagesFile: "compiler:Languages\German.isl"
Name: "italian"; MessagesFile: "compiler:Languages\Italian.isl"
Name: "portuguese"; MessagesFile: "compiler:Languages\Portuguese.isl"
Name: "spanish"; MessagesFile: "compiler:Languages\Spanish.isl"


[CustomMessages]
default.AppCheckError=xxx was not found, please select the Installation Folder of xxx!
spanish.AppCheckError=xxx no fué encontrado, porfavor selecciona la Carpeta de Instalación de xxx!
french.AppCheckError=xxx n'a pas été trouvé, s'il vous plaît sélectionnez le dossier d'installation de xxx!
german.AppCheckError=xxx nicht gefunden wurde, wählen Sie bitte das Installationsverzeichnis von xxx!
catalan.AppCheckError=xxx no s'ha trobat, si us plau, seleccioneu la carpeta d'instal · lació de xxx!
italian.AppCheckError=xxx non è stato trovato, si prega di selezionare la cartella di installazione di xxx!
portuguese.AppCheckError=xxx não foi encontrado, selecione a pasta de instalação do xxx!


[Files]
Source: "xxx\*"; DestDir: {app}; Flags: ignoreversion recursesubdirs createallsubdirs; 
Source: ISSkin.dll; DestDir: {tmp}; Flags: dontcopy; 
Source: Styles\LegendsIV.cjstyles; DestDir: {tmp}; Flags: dontcopy
Source: IsUtilsHb.dll; DestDir: {tmp}; Flags: dontcopy; 
Source: SplashScreen.png; DestDir: {tmp}; Flags: dontcopy;
Source: "BASS_Files\*";  DestDir: {tmp}; Flags: dontcopy
Source: Music.mp3;  DestDir: {tmp}; Flags: dontcopy
Source: logo.png; Flags: dontcopy; DestDir: {tmp}; 
Source: ISLogo.dll; Flags: dontcopy; DestDir: {tmp}; 

; --- Generated by InnoSetup Script Joiner version 3.0, Jul 22 2009, (c) Bulat Ziganshin <Bulat.Ziganshin@gmail.com>. More info at http://issjoiner.codeplex.com/

; --- Source: Verificar ExE.iss ------------------------------------------------------------
[code]
function NextButtonClick1(PageId: Integer): Boolean;
begin
    Result := True;
    if (PageId = wpSelectDir) and not FileExists(ExpandConstant('{app}\left4dead2.exe')) then begin
        MsgBox(ExpandConstant('{cm:AppCheckError}'), mbInformation, MB_OK);
        Result := False;
        exit;
    end;
end;

[Setup]


; --- Source: About.iss ------------------------------------------------------------
[Code]
{ RedesignWizardFormBegin } // Don't remove this line!
// Don't modify this section. It is generated automatically.
var
  AboutButton: TNewButton;
  URLLabel: TNewStaticText;

procedure AboutButtonClick(Sender: TObject); forward;
procedure URLLabelClick(Sender: TObject); forward;

procedure RedesignWizardForm;
begin

  { AboutButton }
  AboutButton := TNewButton.Create(WizardForm);
  with AboutButton do
  begin
    Name := 'AboutButton';
    Parent := WizardForm;
    Left := ScaleX(10);
    Top := ScaleY(327);
    Width := ScaleX(75);
    Height := ScaleY(23);
    Caption := 'Info';   // aqui se escribe lo que quiero ver en el about
    OnClick := @AboutButtonClick;
  end;

  { URLLabel }
  URLLabel := TNewStaticText.Create(WizardForm);
  with URLLabel do
  begin
    Name := 'URLLabel';
    Parent := WizardForm;
    Cursor := crHand;
    Caption := 'WEB'; // nombre q desea poner q redirecciona al enlace
    Font.Color := clRed;  // color
    Font.Height := -11;
    Font.Name := 'Tele-Marines'; //nombre del font
    ParentFont := False;
    OnClick := @URLLabelClick;
    Left := ScaleX(105);
    Top := ScaleY(335);
    Width := ScaleX(97);
    Height := ScaleY(14);
  end;

  AboutButton.TabOrder := 5;
  URLLabel.TabOrder := 6;

end;

procedure URLLabelClick(Sender: TObject);
var
  ErrorCode: Integer;
begin
  ShellExecAsOriginalUser('open', 'www.example.com', '', '', SW_SHOWNORMAL, ewNoWait, ErrorCode);
end;                        //aqui ponen el enlace de su perfil o pagina

procedure AboutButtonClick(Sender: TObject);
begin
  MsgBox('Version 2xxx XXX', mbInformation, mb_Ok);
end;    //edit the version file here

procedure InitializeWizard2();
begin
  RedesignWizardForm;

end;

[Setup]


; --- Source: Audio.iss ------------------------------------------------------------
[code]
procedure InitializeWizard3();
begin
  ExtractTemporaryFile('BASS.dll');
  ExtractTemporaryFile('Music.mp3');

  BASS_Init(ExpandConstant('{tmp}\Music.mp3')) // se copea en los temporarles de tu pc
end;

[Setup]


; --- Source: LOGO XXX.iss ------------------------------------------------------------
[Code]
procedure Logo_Init(Wnd :HWND); external 'ISLogo_Init@files:ISLogo.dll stdcall';
procedure Logo_Draw(FileName: PChar; X, Y: Integer); external 'ISLogo_Draw@files:ISLogo.dll stdcall';
procedure Logo_Free(); external 'ISLogo_Free@files:ISLogo.dll stdcall';

procedure InitializeWizard4();
var
LogoPanel: TPanel;
begin
LogoPanel := TPanel.Create(WizardForm);
with LogoPanel do begin
Top := 326;
Left := 140;
Width := 100;
Height := 37;
Parent := WizardForm;
BevelOuter := bvNone;
end
ExtractTemporaryFile('logo.png');
Logo_Init(LogoPanel.Handle)
Logo_Draw (ExpandConstant('{tmp}\logo.png'), 0 , 0);
end;

[Setup]


; --- Source: Skin Setup.iss ------------------------------------------------------------
[Code]
// Importing LoadSkin API from ISSkin.DLL
procedure LoadSkin(lpszPath: String; lpszIniFileName: String);
external 'LoadSkin@files:isskin.dll stdcall';

// Importing UnloadSkin API from ISSkin.DLL
procedure UnloadSkin();
external 'UnloadSkin@files:isskin.dll stdcall';

// Importing ShowWindow Windows API from User32.DLL
function ShowWindow(hWnd: Integer; uType: Integer): Integer;
external 'ShowWindow@user32.dll stdcall';

function InitializeSetup5(): Boolean;
begin
    ExtractTemporaryFile('LegendsIV.cjstyles');
    LoadSkin(ExpandConstant('{tmp}\LegendsIV.cjstyles'), '');
    Result := True;
end;

procedure DeinitializeSetup5();
begin
    // Hide Window before unloading skin so user does not get
    // a glimse of an unskinned window before it is closed.
    ShowWindow(StrToInt(ExpandConstant('{wizardhwnd}')), 0);
    UnloadSkin();
end;

[Setup]


; --- Source: Splashpng.iss ------------------------------------------------------------
[Code]
function SplashScreen(hWnd: Integer; pathPng: String; nSleep: Integer): Integer;
external 'SplashScreen@files:IsUtilsHb.dll stdcall';

procedure InitializeWizard6();
var SplashFileName: String;
begin
SplashFileName := ExpandConstant('{tmp}\SplashScreen.png');
ExtractTemporaryFile('SplashScreen.png');
SplashScreen (StrToInt(ExpandConstant('{hwnd}')), SplashFileName, 2000);
end;

[Setup]


; --- Source: Texto Transparente Banner.iss ------------------------------------------------------------
[code]
var
  PageNameLabel, PageDescriptionLabel: TLabel;

procedure InitializeWizard7();
begin

  PageNameLabel := TLabel.Create(WizardForm);
  with PageNameLabel do
  begin
    Left := ScaleX(10); // mover el titulo de arriba (menor izq o mayor der)
    Top := ScaleY(10);
    Width := ScaleX(300); // ancho del titulo de texto arriba
    Height := ScaleY(14); // altura del titulo de texto de arriba
    AutoSize := False;
    WordWrap := True;
    Font.Color := clWhite; // color de texto
    Font.Style := [fsBold];
    ShowAccelChar := False;
    Transparent := True;
    Parent := WizardForm.MainPanel;
  end;

  PageDescriptionLabel := TLabel.Create(WizardForm);
  with PageDescriptionLabel do
  begin
    Left := ScaleX(15); // mover la descripcion de abajo (menor izq o mayor der)
    Top := ScaleY(25);
    Width := ScaleX(475); // ancho de la descripcion de texto abajo
    Height := ScaleY(30); // altura de la descripcion de texto abajo
    AutoSize := False;
    WordWrap := True;
    Font.Color := clWhite; // color de texto
    ShowAccelChar := False;
    Transparent := True;
    Parent := WizardForm.MainPanel;
  end;

  with WizardForm do
  begin
    PageNameLabel.Hide;
    PageDescriptionLabel.Hide;
    with MainPanel do
    begin
      with WizardSmallBitmapImage do
      begin
        Left := ScaleX(0); // mover la imagen  (menor izq o mayor der)
        Top := ScaleY(0);
        Width := Mainpanel.Width;
        Height := MainPanel.Height;
      end;
    end;
  end;
end;


procedure CurPageChanged7(CurPageID: Integer);
begin
  PageNameLabel.Caption := WizardForm.PageNameLabel.Caption;
  PageDescriptionLabel.Caption := WizardForm.PageDescriptionLabel.Caption;
end;

[Setup]


; --- Source: Texto Transparente Menú.iss ------------------------------------------------------------
[code]
function NextButtonClick8(CurPageID: Integer): Boolean;
begin
  Result := True;
end;

function GetCustomSetupExitCode8(): Integer;
begin
  Result := 1;
end;

procedure InitializeWizard8();
var
  WLabel1, WLabel2,
  FLabel1, FLabel2: TLabel;
begin
  WizardForm.WelcomeLabel1.Hide;
  WizardForm.WelcomeLabel2.Hide;
  WizardForm.FinishedHeadingLabel.Hide;
  WizardForm.FinishedLabel.Hide;
  WizardForm.WizardBitmapImage.Width := 500; // tamaño de imagen bienvendia ancho
  WizardForm.WizardBitmapImage.Height := 315; // tamaño de imagen bienvendia altura

  WLabel1 := TLabel.Create(WizardForm); // PAGINA BIENVENIDO..
  WLabel1.Left := ScaleX(40); // mover el titulo de arriba (menor izq o mayor der)
  WLabel1.Top := ScaleY(30);
  WLabel1.Width := ScaleX(301); // ancho del cuadro de texto arriba
  WLabel1.Height := ScaleY(65); // altura del cuadro de texto de arriba
  WLabel1.AutoSize := False;
  WLabel1.WordWrap := True;
  WLabel1.Font.Name := 'Arial'; // nombre del font
  WLabel1.Font.Size := 13; // tamaño de texto
  WLabel1.Font.Style := [fsBold];
  WLabel1.Font.Color:= clWhite; // color de texto  
  WLabel1.ShowAccelChar := False;
  WLabel1.Caption := WizardForm.WelcomeLabel1.Caption;
  WLabel1.Transparent := True;
  WLabel1.Parent := WizardForm.WelcomePage;

  WLabel2 :=TLabel.Create(WizardForm);
  WLabel2.Top := ScaleY(110);
  WLabel2.Left := ScaleX(40); // mover el titulo de abajo (menor izq o mayor der)
  WLabel2.Width := ScaleX(301); // ancho del cuadro de texto abajo
  WLabel2.Height := ScaleY(300); // altura del cuadro de texto de abajo
  WLabel2.AutoSize := False;
  WLabel2.WordWrap := True;
  WLabel2.Font.Name := 'arial'; // nombre del font
  WLabel2.Font.Color:= clWhite; // color de texto
  WLabel2.ShowAccelChar := False;
  WLabel2.Caption := WizardForm.WelcomeLabel2.Caption;
  WLabel2.Transparent := True;
  WLabel2.Parent := WizardForm.WelcomePage;

  WizardForm.WizardBitmapImage2.Width := 500; // tamaño de imagen final ancho
  WizardForm.WizardBitmapImage2.Height := 315; // tamaño de imagen final altura

  FLabel1 := TLabel.Create(WizardForm); // PAGINA FINAL..
  FLabel1.Left := ScaleX(40); // mover el titulo de arriba (menor izq o mayor der)
  FLabel1.Top := ScaleY(100);
  FLabel1.Width := ScaleX(301); // ancho del cuadro de texto arriba
  FLabel1.Height := ScaleY(75); // altura del cuadro de texto de arriba
  FLabel1.AutoSize := False;
  FLabel1.WordWrap := True;
  FLabel1.Font.Name := 'arial'; // nombre del font
  FLabel1.Font.Size := 16; // tamaño de texto
  FLabel1.Font.Style := [fsBold];
  FLabel1.Font.Color:= clWhite; // color de texto
  FLabel1.ShowAccelChar := False;
  FLabel1.Caption := WizardForm.FinishedHeadingLabel.Caption;
  FLabel1.Transparent := True;
  FLabel1.Parent := WizardForm.FinishedPage;

  FLabel2 :=TLabel.Create(WizardForm);
  FLabel2.Top := ScaleY(110);
  FLabel2.Left := ScaleX(40); // mover el titulo de abajo (menor izq o mayor der)
  FLabel2.Width := ScaleX(301); // ancho del cuadro de texto abajo
  FLabel2.Height := ScaleY(300); // altura del cuadro de texto de abajo
  FLabel2.AutoSize := False;
  FLabel2.WordWrap := True;
  FLabel2.Font.Name := 'arial'; // nombre del font
  FLabel2.Font.Color:= clWhite; // color de texto
  FLabel2.ShowAccelChar := False;
  FLabel2.Caption := WizardForm.FinishedLabel.Caption;
  FLabel2.Transparent := True;
  FLabel2.Parent := WizardForm.FinishedPage;
end;

[Setup]


; --- Dispatching code ------------------------------------------------------------

[Code]

function NextButtonClick(CurPageID: Integer): Boolean;
begin
  Result := NextButtonClick1(CurPageID); if not Result then exit;
  Result := NextButtonClick8(CurPageID); if not Result then exit;
end;

procedure InitializeWizard();
begin
  InitializeWizard2();
  InitializeWizard3();
  InitializeWizard4();
  InitializeWizard6();
  InitializeWizard7();
  InitializeWizard8();
end;

procedure DeinitializeSetup();
begin
  DeinitializeSetup5();
end;

function InitializeSetup(): Boolean;
begin
  Result := InitializeSetup5(); if not Result then exit;
end;

procedure CurPageChanged(CurPageID: Integer);
begin
  CurPageChanged7(CurPageID);
end;

function GetCustomSetupExitCode(): Integer;
begin
  Result := GetCustomSetupExitCode8(); if Result>0 then exit;
end;


[Registry]
Root: HKCU; SubKey: {app}\XXXTeam; ValueType: string; ValueName: InstallPath;
Root: HKCU; SubKey: {app}\XXXTeam; ValueType: string; ValueName: Version;

[Ini]
Filename: "rev.ini"; Section: Emulator; Key: Language;
Filename: "rev.ini"; Section: steamclient; Key: PlayerName;

回答1:

If you put the lines from the [Languages] section into a separate file (in this case the c:\Languages.txt), the following preprocessor script will generate the script that will add to the combo box placed on a custom page list of available languages and select the current one. On that custom page will also be the edit box for entering player's name. The name of the language along with the entered name will then be stored in the Setup.ini file into a selected application directory. The preprocessed script is saved as c:\PreprocessedScript.iss file.

Languages.txt content:

Note, that each item in the Languages.txt file must have the exact format:

  • the name and language file (path) must be enclosed by the "" chars
  • the file (path) must contain only one file (you cannot use delimited list of files)

Name: "default"; MessagesFile: "compiler:Default.isl"
Name: "catalan"; MessagesFile: "compiler:Languages\Catalan.isl"
Name: "french"; MessagesFile: "compiler:Languages\French.isl"
Name: "german"; MessagesFile: "compiler:Languages\German.isl"
Name: "italian"; MessagesFile: "compiler:Languages\Italian.isl"
Name: "portuguese"; MessagesFile: "compiler:Languages\Portuguese.isl"
Name: "spanish"; MessagesFile: "compiler:Languages\Spanish.isl"

Script file:

The ConvertLanguageName function is borrowed (and modified) from the InnoSetup source...

#define LanguageFile "c:\Languages.txt"
#define LanguageName
#define LanguageIndex
#define LanguageCount
#define FileLine
#define FileHandle
#dim LanguageList[65536]
#sub ProcessFileLine
  #if FileLine != ""
    #expr LanguageList[LanguageCount] = FileLine
    #expr LanguageCount = ++LanguageCount
  #endif  
#endsub
#for {FileHandle = FileOpen(LanguageFile); \
  FileHandle && !FileEof(FileHandle); \
  FileLine = FileRead(FileHandle)} \
  ProcessFileLine
#if FileHandle
  #expr FileClose(FileHandle)
#endif
[Setup]
AppName=My Program
AppVersion=1.5
DefaultDirName={pf}\My Program

[Languages]
#sub AddLanguageItemSection
  #emit LanguageList[LanguageIndex]
#endsub
#for {LanguageIndex = 0; LanguageIndex < LanguageCount; LanguageIndex++} AddLanguageItemSection

[INI]
Filename: "{app}\Setup.ini"; Section: "Emulator"; Key: "Language"; String: "{code:GetLanguageName}"; Flags: createkeyifdoesntexist 
Filename: "{app}\Setup.ini"; Section: "SteamClient"; Key: "PlayerName"; String: "{code:GetPlayerName}"; Flags: createkeyifdoesntexist

[Code]
var  
  NameEdit: TNewEdit;
  LanguageCombo: TNewComboBox;
  LanguageNames: TStringList;

function ConvertLanguageName(const Value: string): string;
var
  I: Integer;
  WideCharCode: Word;
begin
  Result := '';
  I := 1;
  while I <= Length(Value) do 
  begin
    if Value[I] = '<' then 
    begin
      WideCharCode := StrToInt('$' + Copy(Value, I + 1, 4));
      I := I + 6;
    end
    else 
    begin
      WideCharCode := Ord(Value[I]);
      I := I + 1;
    end;
    SetLength(Result, Length(Result) + 1);
    Result[Length(Result)] := Chr(WideCharCode);
  end;
end;

function GetLanguageName(const Value: string): string;
begin
  Result := LanguageNames[LanguageCombo.ItemIndex];
end;

function GetPlayerName(const Value: string): string;
begin
  Result := NameEdit.Text;
end;

procedure InitializeWizard;
var
  PlayerSettingsPage: TWizardPage;
  NameLabel: TLabel;
  LanguageLabel: TLabel;
begin
  PlayerSettingsPage := CreateCustomPage(wpWelcome, 'Caption', 'Description');

  NameLabel := TLabel.Create(WizardForm);
  NameLabel.Parent := PlayerSettingsPage.Surface;
  NameLabel.Left := 0;
  NameLabel.Top := 0;
  NameLabel.Caption := 'Name';
  NameEdit := TNewEdit.Create(WizardForm);
  NameEdit.Parent := PlayerSettingsPage.Surface;
  NameEdit.Left := 0;
  NameEdit.Top := NameLabel.Top + NameLabel.Height + 4;
  NameEdit.Width := 250;

  LanguageNames := TStringList.Create;
  #sub AddLanguageInternalNames
    #define GetLanguageInternalName(str S) \
      Local[0] = Copy(S, Pos("Name:", S) + Len("Name:")), \
      Local[1] = Copy(Local[0], Pos("""", Local[0]) + 1), \
      Copy(Local[1], 1, Pos("""", Local[1]) - 1)
    #emit '  LanguageNames.Add(''' + GetLanguageInternalName(LanguageList[LanguageIndex]) + ''');'    
  #endsub
  #for {LanguageIndex = 0; LanguageIndex < LanguageCount; LanguageIndex++} AddLanguageInternalNames

  LanguageLabel := TLabel.Create(WizardForm);
  LanguageLabel.Parent := PlayerSettingsPage.Surface;
  LanguageLabel.Left := 0;
  LanguageLabel.Top := NameEdit.Top + NameEdit.Height + 8;
  LanguageLabel.Caption := 'Language';
  LanguageCombo := TNewComboBox.Create(WizardForm);
  LanguageCombo.Parent := PlayerSettingsPage.Surface;
  LanguageCombo.Left := 0;
  LanguageCombo.Top := LanguageLabel.Top + LanguageLabel.Height + 4;
  LanguageCombo.Width := NameEdit.Width; 
  LanguageCombo.Style := csDropDownList;  
  #sub AddLanguageDisplayNames
    #define GetLanguageDisplayName(str S) \
      ReadIni(S, "LangOptions", "LanguageName")
    #define GetLanguageFile(str S) \
      Local[0] = Copy(S, Pos("MessagesFile:", S) + Len("MessagesFile:")), \
      Local[1] = Copy(Local[0], Pos("""", Local[0]) + 1), \
      StringChange(Copy(Local[1], 1, Pos("""", Local[1]) - 1), "compiler:", CompilerPath)
    #expr LanguageName = GetLanguageDisplayName(GetLanguageFile(LanguageList[LanguageIndex]))
    #emit '  LanguageCombo.Items.Add(ConvertLanguageName(''' + LanguageName + '''));'
  #endsub
  #for {LanguageIndex = 0; LanguageIndex < LanguageCount; LanguageIndex++} AddLanguageDisplayNames
  LanguageCombo.ItemIndex := LanguageNames.IndexOf(ActiveLanguage);
end;

procedure DeinitializeSetup;
begin
  LanguageNames.Free;
end;

#expr SaveToFile("c:\PreprocessedScript.iss")