A guide to systems for creating installers. Creating an installation distribution package for the program Creating installation packages in inno setup
For the convenience of installing your programs on users' computers, you will need to create a distribution kit. Today I want to talk about a very powerful and free tool for creating distributions for Windows - Inno Setup.
About Inno Setup
Inno Setup appeared in 1997, today it competes with paid installers and even surpasses many of them in terms of the number of functions and stability. The project home page is located at .
Here are the key features of the installer:
- Support for all versions Windows, beginning with Windows 2000, including: Windows 8, Windows Server 2012, Windows 7, Windows Server 2008 R2, Windows Vista, Windows Server 2008, Windows XP, Windows Server 2003 And Windows 2000. This does not require any service packs.
- Extensive support for installing 64-bit applications on 64-bit versions Windows. Architecture support x64 and Itanium(if used Windows Server 2003 on the Itanium architecture, Service Pack 1 or later is required to install 64-bit mode).
- The ability to create a distribution kit consisting of a single EXE file for easy distribution on the Internet. Disk partitioning is also supported.
- Standard setup wizard interface in style Windows 2000/XP.
- Custom installation types such as Complete, compact, Selective.
- Extensive uninstallation options.
- File Installation: Includes integrated compression support deflate, bzip2 And 7-Zip LZMA/LZMA2. The installer can compare file versions, replace used files, use a common file count, register DLL/OCX And type libraries and install fonts.
- Create shortcuts anywhere, including start menu And Desktop.
- Creating elements registry And INI files.
- Running other programs before, during, and after installation.
- Creation multilingual distributions, including languages written from left to right.
- Creation password-protected and encrypted distributions.
- Support digital signature during installation and removal.
- Hidden installation and removal.
- Support Unicode.
- Built-in preprocessor for additional customization at compile time.
- Built-in script processor Pascal to perform additional steps during installation and uninstallation.
- Free source code ( Borland Delphi 2.0-5.0 And 2009 ).
Big plus Inno Setup is that it can be used absolutely free even for commercial use. Although you can make a donation as a thank you or to support the installer. There is also a list of everyone who donated from $100.
This is how the start page of the standard distribution installation wizard created with Inno Setup.
About creating a distribution in Inno Setup
Creating a distribution with Inno Setup happens like this:
1. First you create Inno Setup script. Inno Setup Script is a text file with the extension .iss, which contains the properties of the distribution and a set of actions performed during installation and removal. The script can be created using a standard editor Inno Setup(see picture) or using one of the third party editors such as Inno Script Studio or ISTool. In this article, I will consider using only the standard editor. Inno Setup.
2. Then you compile the script to get a distribution.
3. After compiling, you can test and debug the resulting distribution by installing and uninstalling.
Install Inno Setup
To create distributions with Inno Setup just install the compiler Inno Setup to your computer. The distribution can be downloaded. You can find the download link for the latest stable release in the Stable Release section. At the time of writing, the latest version Inno Setup was 5.5.5 , see the picture. To download the distribution, click on the link " random site» next to the version with support Unicode(file isetup-5.5.5-unicode.exe) or without it ( ANSI version - file isetup-5.5.5.exe). To avoid problems with displaying the Cyrillic alphabet, it is better to immediately use Unicode-option Inno Setup.
If you are going to encrypt your future distribution, then the encryption module ISCrypt.dll you need to download it separately in the Encryption Module section, see the picture (below you see a link to the source codes of this module - ISCrypt.zip).
On the same page, in the QuickStart Pack section, you can find a link to distributions ispack-5.5.5.exe And ispack-5.5.5-unicode.exe for installation Inno Setup together with Inno Script Studio, see the picture. Inno Script Studio is a third party development Kymoto Solutions) that offers you a nice user interface and gives you the ability to debug your installer at runtime. Also, this distribution will offer to download and install the encryption module ISCrypt.dll automatically.
In addition to all of the above, on the download page there is a Beta Release section, for downloading beta versions Inno Setu p, and , to download the source codes, which I won't focus on.
If you are going to use more advanced script editors Inno Setup, you might also be interested in the Inno Setup Third-Party Files page for a list of third-party developments. Here are some third-party developments we can use in conjunction with Inno Setup:
- Inno Script Studio - user interface and debugger. Installed with distribution Quick Start Pack(see above) or a separate distribution, which you can download from the developer's site. There is Russification.
- Visual & Installer - paid plugin for visual studio(supported Visual Studio 2005, 2008 , 2010 , 2012 And 2013 ) to create distributions with Inno Setup. Also Visual & Installer contains master Graphical Installer Wizard, which allows you to create themed distributions (see examples).
- Inno Download Plugin - library and script Inno Setup, which allow you to download files during the installation of your distribution. There is support for the Russian language. Protocols supported FTP, http And HTTPS.
- InnoTools Downloader is another option similar to Inno Download Plugin, also for downloading files during installation. But there is no localization here, and only FTP And http.
- VCL Styles for Inno Setup / ISSkin / Graphical Installer (the last tool is paid) - tools for changing the appearance of the installation wizard of your distribution.
- InnoScript - automatically creates a script file Inno Setup (.iss) by project file Visual Basic (.vbp or .vbproj). There is Russification.
- - creates a distribution kit for the project Visual Basic from development environment Visual Basic 6.0.
- - allows by file Delphi project ( .dpr) or by library project file Delphi (.dpk) create a list of dependencies needed to create a distribution. with the project Delphi XE3 This tool didn't work for me.
- Inno Setup Script #Includes is a library of functions that you can use during installation. The list of functions can be viewed.
- Inno Setup Easy Translator - editor of language files Inno Setup (.isl). This site has been down since 2013, but don't worry, you can easily create and edit language files with any text editor.
- UninsHs is an extension that allows you to add support for " Repair/Modify/Remove» to your applications.
Also on this list, for some reason, there are still some well-known developments ( list updated 04/13/2015):
- - user interface for working with the script Inno Setup. This program is very similar to Inno Script Studio. If you search, you can find Russification, see the picture.
- InnoIDE- another user interface for working with the script Inno Setup. Website InnoIDE ceased to exist around August 2012 (www.innoide.org), so it makes no sense to use this development. But the archive of the site has been preserved, which can be viewed. You can also download the distribution kit there. Russification for InnoIDE can be found on the Internet.
- InnoSetup Script Joiner - a utility that combines several scripts Inno Setup into one.
- (Inno Setup Unpacker) - unpacker of distributions created with Inno Setup. Console application.
- InnoExtractor is another unpacker, but with a user interface. There is Russification. Worked great with my encrypted test distribution (see picture). As you can see, it gets absolutely all the files, including the files used by the installer, and even the Inno Setup script file.
Actually, after you have decided on the necessary functionality, you can start the installation. Here I will consider only the installation Inno Setup + Inno Script Studio using the package Quick Start Pack(file ispack-5.5.5-unicode.exe). Although it makes no sense to paint all the steps in detail, I will focus only on a few. Check mark " Download and install Inno Script Studio' must be if you want to install Inno Script Studio, check mark " Install Inno Setup Preprocessor" - to install the preprocessor, tick " Download and install encryption support" - to install the module ISCrypt.dll to encrypt the distribution.
First run of Inno Setup Compiler
The only program window Inno Setup is the compiler window. The compiler is launched from the start menu. The first time you run it, you'll see a prompt asking you to create an empty script, launch a script wizard, or open examples or recent files.
If you have no experience with Inno Setup, then examples will come in handy. Let's open some example, press the "OK" button and select one of the examples. After the example has opened, you can evaluate what a simple script looks like. Inno Setup. Also note that the compiler interface is very simple and you will need to write the entire script by hand. You will only find help and examples here.
Using the Wizard to Create an Inno Setup Script
Create a new script Inno Setup you can start from scratch or you can use the script wizard. For example, I will make a distribution kit for installing the program MyProg.exe, which is located in the examples folder (installed with Inno Setup). When launched, the program displays two windows and ends.
To call the script creation wizard window, click on the menu item " File -> New” or in the welcome window, select the option “ Create a new script file using the Script Wizard" and press " OK". The first screen of the wizard will be a welcome screen. Press here " Next >».
On the second screen, enter the application name ( application name), application version ( Application version), application publisher ( Application publisher) and the address of the application website ( Application website). Required fields are marked in bold in the wizard, and the rest can be left blank.
In the next step, you select a folder for your application. By default, as you can see from the picture, this is a folder with the same name as the application name, and it will be created inside the folder Program Files. Check mark " Allow user to change the application folder' will allow the user to change the folder during the installation process. And when setting the checkbox " The Application doesn't need a folder» application folder will not be created at all.
If from the drop-down list " Application destination base folder» you choose « (Custom)”, then in the field located just below, you can set an arbitrary path. For example, in order for your application folder to be on the system drive, you need to specify " (sd)».
As you can see, to specify the system drive, I specified " (sd)" instead of " C:”, because on different computers the system disk may be different. Generally in Inno Setup you will use constants like " (sd)". All constants are surrounded by curly braces and there are a lot of them. Here is a complete list of constants with a brief description (for a full description, see the " Constants» in the help):
Directory constants:
- (app)– application directory, for example, "C:\Porgram Files\My Program".
- (win)– Windows directory, for example, "C:\WINDOWS".
- (sys)– System32 directory, for example, "C:\WINDOWS\SYSTEM".
- (src)– directory where the distribution files are located (this is a temporary folder with unpacked distribution files).
- (sd)– system drive, for example, "C:".
- (pf)– application directory, for example, “C:\Program Files (x86)” (in 64-bit mode, this will be a folder for 64-bit applications). In 32-bit mode, this constant is equivalent to the constant (pf32), and in 64-bit - (pf64).
- (cf)– folder of common files, for example, "C:\Program Files (x86)\Common Files". In 32-bit mode, this constant is equivalent to the constant (cf32), and in 64-bit - (cf64).
- (tmp)– temporary folder used during installation or uninstallation (the folder name will be in the format “C:\WINDOWS\TEMP\IS-xxxxx.tmp”).
- (fonts)- font folder.
- (dotnet11) is the .NET Framework 1.0 root folder.
- (dotnet20)– .NET Framework 2.0 root folder. In 32-bit mode, this constant is equivalent to the constant (dotnet2032), and in 64-bit - (dotnet2064).
- (dotnet40)– .NET Framework 4.0 root folder. In 32-bit mode, this constant is equivalent to the constant (dotnet4032), and in 64-bit - (dotnet4064).
Environment folder constants:
- (group)- Path to the Start menu folder accessible to all users.
- (localappdata)– path to the local (without roaming) Application Data folder.
- (send to)– path to the Send To user folder.
- (userappdata) And (commonappdata)– path to the Application Data folder.
- (usercf)– path to the Common Files user folder (works only for Windows 7 and later versions, for older versions of Windows this constant will be equal to (localappdata)\Programs\Common).
- (user desktop) And (commondesktop)* - path to the desktop folder.
- (userdocs) And (commondocs)- the path to the folder "My Documents" (My Documents).
- (user favorites) And (common favorites)* - path to the Favorites folder.
- (userpf)– path to the user's Program Files folder (works only for Windows 7 and later versions, for older versions of Windows this constant will be equal to (localappdata)\Programs).
- (user programs) And (common programs)* - the path to the "All Programs" (Programs) folder in the "Start" menu.
- (userstartmenu) And (commonstartmenu)* - path to the top level of the start menu.
- (userstartup) And (commonstartup)* - the path to the folder "Startup" (Startup) in the "Start" menu.
- (usertemplates) And (commontemplates)* - path to the "Templates" folder.
* = "common" constants equate to "user" constants if the user lacks administrative privileges or the PrivilegesRequired statement is set to lowest.
Other constants:
- {\} – is used when a slash is required at the end of the path, for example, (app)(\). Otherwise, Inno Setup will remove the last slash.
- (%NAME|DefaultValue) is the value of the environment variable, where NAME is the name of the variable, DefaultValue is the string to be used if the variable does not exist. DefaultValue - optional. Examples: (%COMSPEC) or (%PROMPT|$P$G). If the string uses the characters ",", "|", ")" or "%", then instead of them you need to write "% 2c", "% 7c", "% 7d" and "% 25", respectively.
- (cmd)– full path to the console, for example, Windows\System32\cmd.exe (the COMSPEC environment variable is not used to expand this constant).
- (computer name)– name of the computer on which the installation or uninstallation is being performed (the value returned by the GetComputerName function).
- (drive:Path)- Gets a drive letter with a colon from an arbitrary path. If a UNC path is specified, returns the server and folder, for example, \\SERVER\SHARE. Here too, to write the characters ",", "|", ")" or "%", you need to write "%2c", "%7c", "%7d" and "%25", respectively. Examples are: (drive:(src)), (drive:c:\path\file) or (drive:\\server\share\path\file).
- (group name)- the name of the folder in the Start menu for your menu items, which the user selected during installation. Unlike a constant, (group) returns only the name, not the full path.
- (hwnd)– identifier of the background window of the installer.
- (wizardhwnd)– installer window identifier or 0 if the identifier is not available.
- (ini:Filename,Section,Key|DefaultValue)– value from the INI file, where Filename is the name of the INI file, Section is the name of the section in the INI file, Key is the name of the key in the INI file, DefaultValue is the string to be used if the specified key is not found. Here too, to write the characters ",", "|", ")" or "%", you need to write "%2c", "%7c", "%7d" and "%25", respectively. Example: (ini:(win)\MyProg.ini,Settings,Path|(pf)\My Program).
- (language)– internal name of the selected language.
- (cm:MessageName) And (cm:MessageName,Arguments)– message in the current language, where MessageName is the name of the message, Arguments are the arguments for the message separated by commas. Here too, to write the characters ",", "|", ")" or "%", you need to write "%2c", "%7c", "%7d" and "%25", respectively. Example: (cm:LaunchProgram,Inno Setup).
- (reg:HKxx\SubkeyName,ValueName|DefaultValue) is a string from the registry, where HKxx is the root key of the registry, SubkeyName is the path to the desired key, ValueName is the name of the value (or empty if you want to read the default value for the key), DefaultValue is the string to use if the specified value is not present or the value not a string (REG_SZ or REG_EXPAND_SZ). Here too, to write the characters ",", "|", ")" or "%", you need to write "%2c", "%7c", "%7d" and "%25", respectively. Example: (reg:HKLM\Software\My Program,Path|(pf)\My Program).
- (param:ParamName|DefaultValue) is a parameter passed to the installer on the command line, where ParamName is the name of the parameter, DefaultValue is the string to be used if the specified parameter is not found. Here, to write the characters ",", "|", ")" or "%", you need to write "% 2c", "% 7c", "% 7d" and "% 25", respectively. Example: (param:Path|(pf)\My Program).
- (srcexe)– full path to the installer, for example, C:\SETUP.EXE.
- (uninstall.exe)– full path to the uninstaller created by the installer, for example, C:\Program Files\My Program\unins000.exe. This constant is typically used to create a shortcut to uninstall a program in the Inoo Setup script section. The constant is valid only if the Uninstallable statement is set to yes.
- (sysuserinfoname), (sysuserinfoorg)- the name and organization, respectively, to which Windows is registered. This information is read from the registry.
- (user infoname), (userinfoorg), (userinfoserial)– the name, organization, and serial number respectively specified by the user on the User Information page of the installer wizard (which can be enabled using the UserInfoPage instruction). Typically this information is used to write to the registry or INI for later use.
- (username)– name of the user who launched the installer or uninstaller (using the GetUserName function).
- (log) is the name of the log file, or an empty string if logging is not enabled.
The next step in the Inno Setup Script Wizard allows you to add your application files.
The topmost field selects the main executable file. If you check the box " Allow user to start the application after Setup has finished”, then the user will be prompted to run the application after installation. If your distribution does not have an executable file, then you can check the " The application doesn't have a main executable file". Below is a list of files for your distribution. Here you can add individual files (button " Add file(s)…”) or entire folders (“ Add folder..."). When adding a folder, you will see an additional question whether to include subfolders or not.
After adding folders and files to the list, you will be able to edit each item (button " Edit...”) or delete it (button “ Remove"). In the editing window, you can change many parameters: whether you need to recursively include subfolders (daw " Recurse subfolders”), whether it is necessary to include empty folders (daw “ Include empty subfolders”), base destination folder (fields “ Destination base folder"") and a folder inside the base destination folder (" Destination subfolder»).
For example, we will add only the help file.
The next step of the wizard is the selection of the icons to be created. In field " Application Start Menu folder name» is set to the name of the group in the Start menu. If you check the box " Allow user to change the Start Menu folder name", then the user will be able to change the folder name during installation, and if you check the " Allow user to disable Start Menu folder creation”, then the user will be able to disable the creation of this folder in the Start menu altogether. Check the box " Create an Internet shortcut in the Start Menu folder" And " Create an Uninstall icon in the Start Menu folder» so that the installer creates shortcuts within the group, respectively, to open your site and to remove your application. Checkmarks " Allow user to create a desktop icon" And " Allow user to create a Quick Launch icon' will allow the user to create shortcuts on the desktop and in the Quick Launch group. I'll tick all the boxes.
The next step is to set the license files ( license file) and files with information that will be shown before and after installation. If you have specified a license file, then during installation, the user will have to agree to the license. Files supported .txt And .rtf. I will list the files license.txt And readme.txt from the examples folder.
In the next step, select the supported languages. I will leave English and add Russian.
The next step is to set the parameters for the compiler Inno Setup. In field " custom compiler output folder» specifies the path to the folder where the compiler Inno Setup will save the created distribution. If this field is empty, then the distribution will be created in the same folder as the file .iss. In field " Compiler output base file name» specifies the base name for the distribution file or files. For example, if you have the name " setup”, then when creating a distribution kit consisting of a single file, you will receive a file setup.exe. In field " Custom Setup icon file» you can specify the name of the icon file for the future distribution. If nothing is specified here, the standard icon will be used. In the last field setup password» you can specify a password that the user must provide during installation. If the checkbox " Use the password to encrypt the application files”, then the files in the distribution will be encrypted using the specified password. For example, I will fill in all the fields in my own way.
The next step notifies you that a preprocessor has been found. Inno Setup and suggests using the directives #define to simplify your script. If you want to use the directive #define, leave a check mark Yes, use #define compiler directives". If the checkbox is not checked, then, in the future, you can add directives #define to your script manually.
And finally, the last step has appeared, where we simply click on the button " Finish».
After that, the compiler immediately wants to compile our script. Let's agree and press the button " Yes».
After that, the compiler will warn us that the script has not been saved and offer to do so.
Let's agree (press " Yes") and save the script. After saving, the script was compiled and the distribution kit was ready, in the example this is the file my-setup.exe, was created in the folder that I specified in the wizard at the step " compiler settings". After compilation, you can see how it went in the " compiler output» at the bottom of the compiler window, see picture.
As you can see, everything is simple. Now let's immediately test the finished distribution. Click on the menu item " run -> run" to start the installation of the program.
After creating a script template, you can start adding various advanced actions.
Debugging a distribution in Inno Setup
To debug your distribution, open the script .iss and click on the menu item run -> run" to start the installation of the program. After that, you can monitor internal processes during installation in the " Debug Output”, you can set breakpoints on the lines you need, see the picture.
To check the value of a constant while debugging, click on the menu item " Run -> Evaluate Constant…" and in the raised dialog specify the name of the constant (see picture) and click " OK».
After that, the following window will appear with the result returned by the constant.
To debug the uninstall, click on the menu item " Run -> Target Uninstall", and then " run -> run". And to return back to the installation, click on the item " Run -> Target Setup».
Inno Setup script structure
Scripts in Inno Setup are divided into sections. The name of each section is enclosed in square brackets. Each section contains elements specific to that section. For convenience, you can create multiple sections with the same name. Such sections will be perceived as one. Here is an example:
[ Setup ] AppName =My Program [ Files ] Source : "MYPROG.EXE" ; DestDir : "(app)"
You can comment out lines to be ignored by the compiler by prepending a semicolon.
C-like directive supported in script #include, which forces the compiler to pull lines from the specified arbitrary text file into the place where this directive is. Here is the syntax:
#include "filename.txt"
With the directive #preproc you can specify which preprocessor should be used: inline, directive only support #include, or Inno Setup Preprocessor (ISPP), which supports a lot of directives and functions. The preprocessor is used by default in scripts. ISPP, if it is installed and in files .isl the built-in preprocessor is used. Here is the syntax:
#preproc builtin #preproc ispp
Inno Setup script sections
Here is a complete list of all sections Inno Setup with a short description. A complete description of sections and a list of section elements can be found in the help section " Setup Script Sections».
– this section contains global settings used during installation and uninstallation. Example:
[ Setup ] AppName =My Program AppVersion =1.5 DefaultDirName =( pf ) \My Program DefaultGroupName =My Program
– an optional section that defines installation options ( Complete/compact/Selective), which will be displayed on the page for selecting components to install. Example:
[ Types ] Name : "full" ; Description : "Full installation" Name : "compact" ; Description : "Compact installation" Name : "custom" ; Description : "Custom installation" ; Flags : iscustom
– an optional section that defines the components that will be displayed on the page for selecting components for installation. Example:
[ Components ] Name : "main" ; Description : "Main Files" ; Types : full compact custom; Flags : fixed Name : "help" ; Description : "Help Files" ; Types : full Name : "help\english" ; Description : "English" ; Types : full Name : "help\dutch" ; Description : "Dutch" ; Types : full
– an optional section for creating additional tasks to be performed during installation. The user will see the tasks in the form of radio buttons and will be able to choose whether to perform this or that task or not. Example:
[ Tasks ] Name : desktopicon; Description : "Create a &desktop icon" ; GroupDescription : "Additional icons:" ; Components : main Name : desktopicon\common; Description : "For all users" ; GroupDescription : "Additional icons:" ; Components : main; Flags : exclusive Name : desktopicon\user; Description : "For the current user only" ; GroupDescription : "Additional icons:" ; Components : main; Flags : exclusive unchecked Name : quicklaunchicon; Description : "Create a &Quick Launch icon" ; GroupDescription : "Additional icons:" ; Components : main; Flags : unchecked Name : associate; Description : "&Associate files" ; GroupDescription : "Other tasks:" ; Flags : unchecked
- this optional section defines which additional folders besides the application folder should be created.
[ Dirs ] Name : "(app)\data" Name : "(app)\bin"
– an optional section that determines which files will be installed on the computer.
[ Files ] Source : "CTL3DV2.DLL" ; DestDir : "(sys)" ; Flags : onlyifdoesntexist uninsneveruninstall Source : "MYPROG.EXE" ; DestDir : "(app)" Source : "MYPROG.CHM" ; DestDir : "(app)" Source : "README.TXT" ; DestDir : "(app)" ; Flags : isreadme
– an optional section that determines what shortcuts will be created in the Start menu, on the desktop, etc.
[ Icons ] Name : "(group)\My Program" ; Filename : "(app)\MYPROG.EXE" ; WorkingDir : "(app)" Name : "(group)\Uninstall My Program"; Filename : "(uninstall.exe)"
– an optional section that determines which entries will be added to the INI file.
[ INI ] Filename : "MyProg.ini" ; Section : "InstallSettings" ; Flags : uninsdeletesection Filename : "MyProg.ini" ; Section : "InstallSettings" ; Key : "InstallPath" ; String : "(app)"
And - these optional sections determine which files or folders should be deleted, respectively, on first installation or uninstallation. Example:
[ UninstallDelete ] Type : files ; Name : "(win)\MYPROG.INI"
– section defines the languages that will be available during installation. When you run the installer, the language will match the language of the system. Otherwise, the language that is the first in the section will be used by default. . Example:
[ Languages ] Name : "en" ; MessagesFile : "compiler:Default.isl" Name : "nl" ; MessagesFile : "compiler:Languages\Dutch.isl"
– section for replacing messages described in language files .isl. An example of replacing the standard text " &Next >” on the next step button for English only:
[ Messages ] en.ButtonNext =&Forward >
– section for defining constant values (cm:...), see the description of the constants above. Usage example:
[ CustomMessages] CreateDesktopIcon=Create a &desktop icon [ Tasks ] Name : desktopicon; Description : "(cm:CreateDesktopIcon)"
– section contains language settings, such as font. Example:
[ LangOptions ] LanguageName=English LanguageID=$0409 LanguageCodePage=0 DialogFontName= DialogFontSize=8 WelcomeFontName=Verdana WelcomeFontSize=12 TitleFontName=Arial TitleFontSize=29 CopyrightFontName=Arial CopyrightFontSize=8 RightToLeft=no
- This optional section specifies which keys and values to create, modify, or delete in the registry. Examples of using:
[ Registry ] Root : HKCU ; Subkey : "Software\My Company" ; Flags : uninsdeletekeyifempty Root : HKCU ; subkey: ; Flags : uninsdeletekey Root : HKLM ; Subkey : "Software\My Company" ; Flags : uninsdeletekeyifempty Root : HKLM ; sub key : "Software\My Company\My Program"; Flags : uninsdeletekey Root : HKLM ; sub key : "Software\My Company\My Program\Settings"; ValueType : string ValueName : "InstallPath" ; ValueData : "(app)"
- this optional section defines which programs to run after a successful installation, but before the final step appears in the installation wizard window. Examples:
[ Run ] Filename : "(app)\INIT.EXE" ; Parameters : "/x" Filename : "(app)\README.TXT" ; Description : "View the README file" ; Flags : postinstall shellexec skipifsilent Filename : "(app)\MYPROG.EXE" ; Description : "Launch application" ; Flags : postinstall nowait skipifsilent unchecked
- this optional section determines which programs should be executed at the very beginning of the uninstallation.
– in this optional section you can place your Pascal script. For processing Pascal script engine is used RemObjects Pascal Script. This engine is as free as Inno Setup. Official page of the engine RemObjects Pascal Script- . Usage examples can be found in the files " Code*.iss" And " UninstallCode*.iss" in folder " Examples» at the place of installation Inno Setup.
Order of installation and uninstallation
A very important point during installation is understanding the order in which the script is executed. The installer steps are listed below in the order in which they will be performed during installation:
- Section execution .
- Section elements are stored in the uninstall log (which, at this stage, is stored in memory).
- An application directory is created, if necessary.
- Running sections .
- The name of the uninstall log file is reserved, if necessary.
- Section in progress (files are not registered yet).
- Section in progress .
- Section in progress .
- Section in progress .
- Files that must be registered are registered, except when the system must be rebooted. In the case when a reboot is required, registration occurs only after the system is restarted.
- Add to the list of installed programs (Control Panel\Programs\Programs and Features), if necessary.
- Section elements saved in the uninstall log.
- The EXE file and the uninstaller log are saved to disk. After this point, the user is prevented from canceling the installation, and any subsequent errors will not roll back the installation.
- Section execution , except for the elements of the section with the flag " post-install”, which will be executed after the last step of the installation wizard is displayed.
- Updating associations for files, if the flag " Changes Associations» is set to « yes».
- Notify running applications that environment variables have changed if the " ChangesEnvironment» is set to « yes».
- As for the elements of the section, they will be executed in the order in which they are located inside the section.
Uninstallation occurs in the reverse order. But this does not apply to sections. And , which will be executed in the order in which they occur in the script (not in reverse order).
Inno Setup preprocessor
I would like to write a few words about the preprocessor Inno Setup (ISPP). The main purpose of the preprocessor is to automate tasks at compile time and reduce the likelihood of typos in your scripts. For example, you can declare a variable ISPP(compile-time variable) containing the name of your application, and then use the value of this variable in several places in your script. If for some reason you later need to change the name of your application, you can do so in one place in your script. Without ISPP, you will have to find and fix all parts of the script where you use the application name, for example, AppName, AppVerName, DefaultGroupName etc.
Another use case ISPP- this is pulling information about the version of the application from the EXE file and using it in the instruction AppVerName in section . Without ISPP, you will have to change the script every time you change the application version.
In addition, splitting the script into parts makes it possible to create a single script for different versions of your application (for example, trial and full version).
When using the preprocessor, it is important to remember that the preprocessor only works at compile time.
Calling the Inno Setup compiler from the command line
It will not be superfluous to know about the possibility of compiling the distribution from the command line. The compilation call looks like this:
compil32 /cc
А вот пример:
compil32 /cc "c:\isetup\samples\my script.iss"
Вызов компиляции из командной строки, в данном случае, не скрывает отображение прогресса или сообщений об ошибках. Компилятор возвращает 0, если компиляция прошла успешно, 1, если параметры командной строки переданы неверно, или 2, если компиляция не удалась.
Альтернативный способ компиляции – это использование консольного компилятора ISCC.exe . Вот схема использования компилятора:
iscc [ options]
А вот пример:
iscc "c:\isetup\samples\my script.iss"
Вот основные опции:
/DO
– отключить создание дистрибутива (меняет все параметры Output
в скрипте).
/EO
– включить создание дистрибутива (меняет все параметры Output
в скрипте).
/O
– устанавливает путь, где будет создан дистрибутив (меняет все параметры OutputDir
в скрипте).
/F
– устанавливает имя файла дистрибутива (меняет все параметры OutputBaseFilename
в скрипте).
/S
– настройка параметра SignTool
.
/Q[p]
– для скрытой компиляции (выводятся только сообщения об ошибках, «p
» выводит прогресс).
/?
– для отображения справки.
Вот пример с использованием опций:
iscc /Qp /O"My Output" /F"MyProgram-1.0 " /Sbyparam=$p "c:\isetup\samples\my script.iss"
ISCC возвращает 0, если компиляция прошла успешно, 1, если неправильно указаны параметры или произошла внутренняя ошибка, или 2, если компиляция не удалась.
В заключении об Inno Setup
Рассказать обо всех возможностях Inno Setup не удастся в рамках одной статьи, это очень большой объём информации, поэтому я описал здесь лишь основные моменты. После прочтения вы сможете начать пользоваться этим замечательным инструментом для создания собственных дистрибутивов. В будущем я расскажу про альтернативные пользовательские интерфейсы. А сейчас, пишите ваши комментарии к статье, и я постараюсь ответить на все ваши вопросы.
Большинство пользователей, которые не особо знакомы с компьютером, интересуются, что собой представляет Setup и каковы его функции. Порой ответить на этот вопрос достаточно просто. Однако во многих случаях с этим компонентом связано много проблем на компьютере.
Таким образом, следует разобраться, что такое Setup и понять, что предпринять, если возникли неполадки с данным файлом. Стоит отметить, что это не так уж и сложно, как может показаться на первый взгляд.
Языковые нормы
Прежде всего необходимо понять, что это перевод слова. Довольно часто именно он оказывает помощь пользователю, дает возможность вникнуть в смысл операции. Что представляет собой Setup? Чтобы получить ответ на данный вопрос, следует обратиться к английскому словарю. Это слово в переводе означает «установка» (существительное) или «устанавливать» (глагол). Другими словами, что-то, что выполняет установку на компьютер. Стоит отметить, что без этого компонента трудно представить себе работу операционной системы. Неужели программа Setup настолько важна? Это следует выяснить. Особенно, когда компьютер систематически выдает различные ошибки.
Для компьютера Что такое Setup?
Кроме главного перевода, существуют еще и компьютерная трактовка этого приложения. Она наиболее понятна для современных пользователей. Стоит отметить, что «Сетап» означает программу, предназначенную для установки чего-либо. Основным ее компонентом является Setup.exe. Другими словами, это установочный или исполняемый файл. То, что осуществляется на компьютере после запуска. Чем характеризуется Setup? К примеру, можно выделить среди исполняемых документов различные приложения, игры (их установку), запуск настроек. Также существует и Bios Setup. Это наименование настроек, которые дают возможность работать с компьютером. Другими словами, с популярным всем «Биосом».
Невозможно представить компьютер без «Сетапа». Когда данных файлов нет, пользователь не сможет выполнять разные команды. Невозможно будет и устанавливать контент и программы. Setup.exe присутствует в каждом приложении или игре. Он помогает запустить программу установки, которая позволяет оперативно поставить требуемый контент в операционную систему. Чтобы активировать эту функцию, необходимо два раза совершить щелчок по исполняемому файлу.
Правила обращения
Стоит отметить, что файл Setup.exe нуждается в особом обращении. Особенно, когда речь идет об установке игры, которая скачана из интернета. Следует разобраться, что же помогает в данном непростом деле. Сначала необходимо просто закрыть все сторонние приложения, чтобы избежать возможных сбоев. Далее можно переходить в папку, содержащую исполняемый файл. Для запуска потребуется два раза кликнуть по «Setup.exe». При установленной операционной системе Windows 7 и выше, у пользователя компьютер спросит разрешение начала процесса. На экране всплывет окно с главной информацией об изготовителе-создателе, а также о расположении документа. Там понадобится ответить «Да», чтобы выполнить запуск, или «Нет», чтобы отменить установку чего-либо.
Когда будет выполнено подтверждение, возникнет окно с простой навигацией. Сначала система поприветствует пользователя и оповестит, что будет устанавливаться. Затем нужно придерживаться всех указаний в «Инсталляторе» и завершить процесс. После этого будет установлено определенное приложение. Очень важно никогда не перемещать Setup.exe из корневой папки контента. Также не рекомендуется удалять его и удалять его даже после того, как произойдет установка на компьютер. Это может являться причиной отказа приложений от работы. Стоит отметить, что «Сетап» представляет собой еще и приложение, которое требуется не только для установки чего-либо, а также для запуска. Все ярлыки, содержащиеся на рабочем столе, которые участвуют в активации программ, в результате имеют адрес с расширением «exe».
Процесс
Среди исполняемых процессов можно иногда обнаружить «Сетап». Стоит отметить, что некоторые пользователи настораживаются при этом. Setup работает и следит за выполняемыми и запускаемыми процессами. Таким образом, он выполняет функции некого фильтра. Если его отключить, работа операционной система становится неконтролируемой. Другими словами, невозможно нормально устанавливать и запускать приложения и игры. Поэтому не нужно стараться заниматься данной самодеятельностью. Порой этот процесс занимает много компьютерных ресурсов.
Вирус
Допустим, безопасный ранее «Сетап» способен стать настоящим вирусом. В данном случае он может находиться где-то в операционной системе и шифроваться под обыкновенный исполняемый файл. Такая компьютерная зараза зачастую прикрепляется к приложениям, в которых больше всего возникает необходимость. Вирус активируется постоянно после запуска требуемой программы. Стоит отметить, что антивирус не всегда способен справиться с проблемой. Изначально обнаружить вирус, который замаскирован под «Setup.exe», достаточно тяжело. Если существуют подозрения, что компьютер заражен, придется закрыть все приложения, а также выполнить проверку системы на наличие заразы. В данной ситуации на помощь придет антивирус. Отлично справляются с «Сетапом» следующие программы:
Avast;
Nod32;
Dr.Web.
В случае, когда при выполнении сканирования подтвердились опасения, не нужно спешить удалять угрозу. Необходимо помнить, что после этого не получится запускать приложение, где был вирус. Чтобы произвести эффективное и правильное лечение компьютера, нужно обратиться за помощью к специалистам сервисного центра. Они найдут и обезвредят угрозу, не причинив вреда файлам и документам пользователя.
Шпион
Существует еще один достаточно распространенный вариант развития событий. Речь идет о наличии на компьютере специального шпиона. Он способен шифроваться в таких процессах, как Setup. Данная зараза предназначена для обнаружения и хищения личных данных пользователей. Например, адресов и электронной почты, номеров банковских карт, логинов и паролей от страниц и прочее. Стоит отметить, что не особо приятно выявить на компьютере шпиона, особенно когда он зашифрован под Setup.exe.
Использовать антивирус в данном случае не всегда эффективно. Потребуется дополнительно скачать и установить специальную программу-антишпион. К примеру, SpyHunter. Она пребывает в свободном доступе и проста в использовании. Необходимо запустить приложение, а после этого начать проверку. Когда будут получены результаты, можно смело удалять угрозы. Не нужно забывать и о посещении диспетчера задач и после этого завершить процесс Setup.exe. Далее стоит перезагружать компьютер. «Сетап» вновь окажется в диспетчере, однако пугаться его также не стоит.
Таким образом, в статье был разобран вопрос, что представляет собой Setup. Как можно заметить, что это очень важный файл. Порой он способен принести много проблем. Чтобы избежать неприятностей, следует просто смотреть, что устанавливается на компьютер и скачивается. Рекомендуется всегда запускать только те процессы, которые заслуживают доверие.
Тихая установка - это такой процес, при котором вы тихо-мирно сидите и смотрите на экран, где без вашего участия происходит процесс установки ПО, при условии, что его вообще видно. При этом установщик не беспокоит вас вопросами типа Вы согласны с лицензионным соглашением? . Параметры для установки используются по-умолчанию. т.е. те, которые предлагает установщик при установке ПО обычным способом.
К минусам тихой установки можно отнести всякие панели в обозревателях и ярыки типа E-Bay на рабочем столе, поскольку чаще всего подобные бонусы включены в установку по-умолчанию. Но это скорее исключение, хотя и не редкое. Подробно о тихой установке читайте в этой статье.
На самом деле тихая установка - это очень удобная процедура, которая экономит время и упрощает жизнь системного администратора. Я, например, использую режим silent install после чистой установки ОС.
Режим тихой установки включается при помощи параметров или (как их ещё называют) ключей. Если вы не знаете, что это такое, можете восполнить пробел в знаниях при помощи этой статьи: . Запуск процедуры можно осуществить несколькими способами:
- Из командной строки, используя параметры.
- Аналогично через bat-файл (com-файл).
- Через SFX-архив с файлом конфигурации.
Ключей достаточно много. Какой именно ключ нужно использовать зависит от установщика. Т.е. любая программа, говоря простым языком, это папка с файлами, а запаковывает всё это добро в один файл установки специальный сборщик (система создания установщиков ПО). И вот от того, какой сборщик использовался, зависит - какой ключ будет вызывать режим тихой установки. Наиболее известные системы создания установщиков:
- Install Shield
- WISE Installer
- Inno Setup
Подробнее о ССИ и их ключах можно . Также можно попробовать найти нужный ключ с помощью специального ПО - Universal Silent Switch Finder или почитать документацию на сайте разработчиков той программы, ключи к которой вы ищите.
Во время экспериментов с тихой установкой мне встречались следующие параметры запуска режима тихой установки:
/silent /verysilent /quiet /qb /qn /qr /passive /s /S /qn REBOOT=ReallySuppress /s /v" /qn REBOOT=ReallySuppress
Ключи для отмены перезагрузки:
/norestart /noreboot
Антивирус Avast имеет опцию тихой установки в корпоративной версии. В бесплатной (Home) версии по заявлениям разработчиков тихой установки нет. Однако, если вы в курсе как работает инсталятор InstallShield , вы поймете, что это утверждение не соответствует действительности, поскольку этот инсталятор сам по себе поддерживает ключ тихой установки /S . А значит все продукты, выполненные на его базе - тоже. И Avast Home не исключение.
Для запуска тихой установки архиватора 7Zip (сборщик NSIS) нужно запустить установщик с ключом /S . Положите установщик 7Zip (7z.exe) в корень диска С. Затем откройте меню Пуск › Выполнить (или + R ) и введите в форму следующую команду:
C:7z.exe /SАрхиватор установится без диалоговых окон и признаков внешней активности.
Однако случается что установщик собран нестандартно и ключей для запуска тихой установки у него просто нет. К таким исключениям относится Avira Antivir. По-тихому можно только распаковать содержимое установщика во временную директорию (минус одно окно), а дальше всё. В этом случае приходится создавать специальные самораспаковывающиеся архивы с файлами инструкций внутри. Тут дело обстоит немного сложнее.
Тихая установка с помощью sfx-архивов
Выше я упомянул о случаях, когда вариант с ключами может не работать. Режим тихой установки может быть просто не предусмотрен разработчиком. В этом случае достаточно часто можно выйти из положения, используя sfx-архивы. Sfx-архив - это само-распаковывающийся архив.
Одно из его достоинств в том, что для его распаковки не нужен архиватор. К тому же с помощью него можно существенно расширить возможности тихой установки, да и возможности установки ПО вообще.
Например, сразу после распаковки sfx-архив позволяет запустить один или несколько распакованных файлов, удалить файлы после выполнения операций и много чего ещё. В этих операциях принимают участие конфигурационные файлы, содержащие команды (например, ).
При помощи команд можно имитировать процесс тихой установки. Многие установщики, в том числе и упомянутый в прошлой статье Avira, могут работать с файлами инструкций (подхватывать их), при условии, что инструкция находится в том же каталоге, что и установщик. Подробнее об инструкциях (командах, указывающихся в конфигах) можно узнать на сайте разработчика программы или на соответствующих форумах.
Чтобы в общих чертах представить конфигурационный файл (для тех, кто не в курсе) ниже приведён пример такого файла для программы Firefox Portable
FirefoxDirectory =Appfirefox ProfileDirectory =Dataprofile SettingsDirectory =Datasettings PluginsDirectory =Dataplugins FirefoxExecutable =firefox.exe AdditionalParameters = LocalHomepage =index.html DisableSplashScreen =false AllowMultipleInstances =false DisableIntelligentStart =false SkipCompregFix =false RunLocally =falseСтоит отметить, что возможности и режимы работы программ со временем могут меняться. Firefox Portable может перестать поддерживать ini-файлы, а будущие версии инсталятора Avira - понимать и подхватывать файлы инструкций. Поэтому при экспериментах стоит ознакомиться с актуальной информацией о возможностях программ, которые вы планируете использовать.
Как sfx-архив может помочь процессу тихой установки, я думаю, мы разобрались. Теперь настало время перейти к практической части. Для создания sfx-архивов я пользуюсь доработанным модулем архиватора 7Zip . Весь процесс создания sfx-архива и запуска при помощи него режима тихой установки описан (разработчика модуля). Я же очень кратко перескажу написанное в ней, пояснив пару моментов.
Сразу отмечу, что цель примера - запаковать установщик программы в sfx-архив таким образом, чтобы он после распаковки автоматически начинал устанавливаться по-тихому. В данной статье в качестве подопытного будет выступать установщик архиватора 7Zip (7z465.exe), хотя можно использовать любой другой, главное знать ключ тихой установки. У установщика 7Zip это ключ /S . Итак, для исполнения задуманного нам понадобится:
- Модуль sfх Олега Щербакова.
- Архиватор 7Zip . Им мы будем запаковывать установщик программы в архив формата ".7z". Архиватор, понятное дело, надо установить в систему.
- Установщик программы (как я отметил выше, в примере я использую 7z465.exe).
- Архив.7z , который мы получим, запаковав установщик программы архиватором 7Zip.
- Конфигурационный файл
config.txt, в котором будут содержаться иструкции "поведения" sfx-архива при распаковке, т.е. в данном примере в нём будет содержаться команда на запуск тихой установки.
Заклинание для создания sfx-архива (вводится в консоли).
Для удобства я положил все ингредиенты в один архив, который вы можете скачать . Также, если скачать вот , можно поменять иконку архива (как это сделать ).
Обратите внимание, кодировка файла конфигурации config.txt должна быть UTF-8.
Итак, получаем после скачивания и распаковки папку со всем этим добром, далее по списку:
- Устанавливаем архиватор 7zip (лежит в папке).
- Запаковываем подопытного 7z465.exe (лежит в папке) в 7z-архив. Получаем на выходе файл 7z465.7z.
- Открываем консоль (Пуск › Выполнить - cmd) и переходим в папку с файлами: cd C:files (пример для папки "files" на диске "С").
- Запускаем в консоли заклинание:
- COPY /b 7zsd.sfx + config.txt + 7z465.7z 7Zip.exe
- 7zsd.sfx - имя модуля sfx.
- config.txt - имя файла конфигурации.
- 7z465.7z - имя запакованного установщика 7z465.exe.
- 7Zip.exe - имя sfx-архива на выходе.
В результате получаем sfx-архив 7Zip.exe, который представляет собой исполняемый файл или самораспаковывающийся архив, внутри которого содержится инструкция config.txt. Содержание инструкции следующее:
;!@Install@!UTF-8! RunProgram ="7z465.exe /S" GUIMode ="2" ;!@InstallEnd@!- ;!@Install@!UTF-8!
;!@InstallEnd@! - строки начала и конца файла инструкции. Это комментарии, их можно удалить. А вот остальные две нужны обязательно. - GUIMode="2" - режим распаковки архива без оповещений (по-тихому).
- RunProgram="7z465.exe /S" - строка инструкции, в которую необходимо вносить изменения в зависимости от того, какой установщик вы используете. В строке прописывается имя установщика, который запаковывается в 7z-архив и который требуется установить по-тихому + ключ тихой установки.
На этом всё. Ознакомившись со статьями Олега (ссылки выше), можно создать различные архивы, выполняющие абсолютно разные задачи. Удачных экспериментов!
Часть 1
Знакомство пользователя с программой чаще всего начинается с запуска инсталлятора. Внешний вид («упаковка») и функциональность продукта определяется разработчиком. Пользователю нужно иметь возможность проконтролировать процесс, выставив нужные параметры установки. Для разработчика же важно, чтобы, как минимум, его программа была установлена корректно, а инсталлятор был совместим с необходимыми платформами.
Решений для создания инсталляторов достаточно много. Чаще всего используется подсистема Windows Installer, которая уже входит в инструментарий операционной системы. Но существуют и альтернативные решения - как платные, так и бесплатные, различной функциональности. Зачастую с их помощью можно создавать пакеты с инсталлятором, не зависящим от Windows Installer.
Путеводитель включает в себя всевозможные системы для создания инсталляторов, основные аспекты их обзора следующие:
- Среда разработки, интерфейс, поддержка сценариев
- Работа с проектом, типы создаваемых пакетов, возможности импорта проектов из других сред разработки
- Пользовательские опции инсталлятора: поддержка языков, профилей и другие опции
- Поддержка расширений
NSIS (Nullsoft Scriptable Install System)
NSIS - бесплатный и широко известный инструментарий для создания инсталляционных пакетов в среде Windows. Отличительные особенности - компактность, масштабируемость, поддержка плагинов и локализаций. Из других возможностей NSIS: поддержка сценариев, различных вариантов установки (включая несколько проектов внутри одного инсталлятора), создание веб-инсталляторов.
Дистрибутивы NSIS создаются на основе сценариев. Переменные, функции полностью контролируют как инсталляцию, так и деинсталляцию продукта. С помощью скриптов можно добавлять файлы и директории, вносить изменения в реестр, редактировать текстовые и двоичные файлы, создавать патчи, управлять переменными среды и даже обращаться к Windows API (посредством расширений).
Синтаксис языка NSIS достаточно прост и удобен для чтения, основная документация к нему доступна . Более того, в комплекте с программой содержится большое количество примеров (файлы формата nsi доступны в папке Examples). Для редактирования nsi-сценариев пригоден любой редактор кода, где без особых усилий можно включить подсветку синтаксиса. Множество задач сразу унифицируется, если использовать специальный плагин для IDE Eclipse, либо . Venis представляет собой интуитивную визуальную среду для создания сценариев.
Удобно работать с NSIS в связке и с другими программами, например, (см. ниже).
Если возникает необходимость расширить возможности инсталлятора, можно добавить определенные функции. Плагины пишутся на C, C++, Delphi или других языках. Готовые примеры расширений доступны . Функции разнообразны: от визуальных эффектов инсталлятора до создания патчей и обращения к Windows API.
Скомпилировать инсталлятор можно с помощью инструмента makensis, предварительно выбрав тип компрессии - ZLib, BZip2 или LZMA. Кроме того, сам по себе инсталлятор занимает немного места - всего 34 КБ.
Графический интерфейс инсталлятора доступен в одном из двух вариантах исполнения - Classic или Modern. Более функциональный Modern (на данный момент используется его версия 2.0) позволяет создавать страницы мастера установки с использованием текста, шрифтов, изображений, диалогами, опциями и др. На данном этапе помощь окажет программа . Она позволяет быстро конструировать интерфейс, а полученный результат сохранять в формат nsdinc, который затем несложно интегрировать в.nsi-скрипт.
Резюме . Среда NSIS уже давно зарекомендовала себя, и в доказательство - , которые используют ее возможности. Несложный язык сценариев, наличие всех необходимых функций, возможность расширения, доступность основных и дополнительных инструментов - за счет всего этого NSIS составляет сильную конкуренцию программам в данной категории.
Inno Setup
Inno Setup - бесплатный инструментарий для создания инсталляторов на базе сценариев. Среди главных особенностей продукта - работа со всеми версиями ОС Windows (Windows 2000 и выше), расширенная поддержка 64-битных приложений, настраиваемые типы установки, встроенный препроцессор и мощный язык сценариев на основе Pascal.
Сценарии имеют структуру, характерную конфигурационным файлам ini-формата, поэтому код вполне хорошо читаем и удобен в редактировании. Документ разделен на секции, и каждая из них отвечает за определенную задачу инсталлятора соответственно. Всего имеется два типа секций - с параметрами и «директива-значение».
Разработчикам, знакомым с Pascal, будет на руку тот факт, что Inno использует «родственный» язык - . Сценарии отвечают за добавление новых опции, создание интерфейса, вызов файлов или библиотек, настраиваемые действия (custom actions) и т. д. В рабочей папке Inno Setup находятся примеры скриптов (также доступны в меню компилятора). По умолчанию в Inno Setup входит компилятор сценариев Compiler IDE. Для быстрого старта рекомендуется также установить Inno Script Studio. Этот редактор проектов входит в редакцию QuickStart Pack, скачать ее можно . Для упрощения задач может быть полезен визуальный редактор сценариев - .
Самый простой вариант создания инсталлятора - обратиться к пошаговому мастеру настройки Inno Script Studio. Здесь указывается информация о продукте, координаты программы, файл лицензии и другие данные, языки локализации, опции компилятора. Впоследствии проект доступен для компиляции, отладки либо модификации полученного сценария в окне редактора.
Редактор Inno Script Studio доступен на русском языке. Значительно проще настраивать проект последовательно, переходя по секциям, а не создавая сценарий с нуля. При добавлении нового элемента изменения вносятся в код сценария, синтаксис подсвечивается, код соответствующим образом разбит на секции (, , …).
Разделы редактора не сгруппированы, но структура вполне узнаваема. Логически их можно разделить следующим образом:
- Содержимое дистрибутива: Файлы, Каталоги, Иконки, Файлы INI, Реестр
- Сообщения и пользовательские сообщения,
- Пользовательские опции: Типы, Компоненты, Задачи, Языки
- Действия: Выполнить, Удалить перед установкой, Выполнить перед деинсталляцией, Удалить после деинсталляции
- Код сценария: Код Паскаля, Этапы предкомпиляции, Этапы посткомпиляции
Русская локализация иногда вводит в заблуждение, как всегда и обстоит с не очень качественным переводом.
Из других особенностей Inno Setup - тихая инсталляция и деинсталляция. Пользователю доступны различные типы установки и локализации на выбор. Установщик может быть зашифрован, содержать цифровую подпись либо защищен паролем. К дистрибутиву может применяться bzip2- или LZMA/LZMA2-компрессия. Интерфейс - в стиле 2000/XP, иных вариантов не предусмотрено.
Резюме . Inno Setup - ближайшая альтернатива NSIS. Позволяет задействовать как мощный язык сценариев, так и удобный и гибко настраиваемый редактор Inno Script Studio, доступный практически «из коробки».
IzPack
Чаще всего, среда разработки инсталлятора закреплена за определенной платформой, и разработчик вынужден использовать различный инструментарий для каждой из них. IzPack решает вопрос кроссплатформенности, используя для своих нужд универсальную среду разработки Java.
Главные особенности IzPack: XML-синтаксис, интеграция с различными инструментами компиляции, простой и гибкий API-интерфейс, возможность локализации.
Среди особенностей инсталляторов, созданных средствами IzPack, - небольшой размер и модульность. В основе дистрибутива лежит XML-документ, где указываются все необходимые спецификации, определяется функциональность продукта. Впоследствии конфигурационный файл обрабатывается любым удобным способом, для этого используется командная строка или . Для наращивания функциональности инсталлятора могут быть задействованы IDE среды, такие как Eclipse, IntelliJ IDEA или Netbeans. Для составления конфигурационного файла подойдет любой редактор кода.
В XML-документе указывается информация о проекте (), интерфейс (), локализации (), файлы (), ресурсы (), панели (), содержимое (- может быть упаковано в raw, gzip, bzip2) и др. Что касается java, в IzPack есть возможность применения действий (custom acrions) и переменных - встроенных, пользовательских и переменных среды (см. и ).
Для создания графического интерфейса инсталлятора предназначены панели. С их помощью определяется внешний вид, экрана приветствия, содержимое, текстовая информация (readme, лицензии), изображения. Поддерживаются различные типы интерактивных элементов (поля, переключатели и т. д.), локализация, включая русскую. Переводу поддается как интерфейс, так и содержание.
Для создания самораспаковывающихся модулей применяется метод 7-Zip SFX, использующий возможности известного архиватора. Для Mac OS также доступна оболочка под названием izpack2app.Кроме того, есть возможность создания веб-инсталлятора, для этих целей присутствует оболочка izpack2jnlp, использующая возможности Java Web Start. IzPack поддерживает опцию тихой установки.
Резюме . IzPack - одна из немногих кроссплатформенных систем для создания инсталляторов. Процесс написания конфигурации, компиляции и отладки удобен за счет интеграции со средами разработки, несложен в освоении. Из недостатков следует отметить значительно устаревший (и не оригинальный - native) вид получаемого инсталлятора.
Excelsior Installer
Excelsior Installer - бесплатная программа, предназначенная для создания инсталляторов и обновлений. Основные особенности - простая интуитивная графическая оболочка, возможность интеграции с Проводником и NSIS.
Создание дистрибутива или обновления производится с помощью упаковщика (Packager). Он содержит пошаговый мастер, содержащий настройки проекта. На основе проекта очень просто скомпилировать восьмишаговый инсталлятор. Согласно описанию, это делается и вовсе двумя кликами мыши, но в обязательном порядке в упаковщике необходимо определить следующие параметры:
- Файлы и папки приложения, ярлыки
- Описание: имя компании, название продукта, версия продукта
Упаковщик состоит из разделов Files (Файлы), Settings (Настройки) и Appearance (Внешний вид). В целом, здесь содержится стандартный перечень опций, отвечающих за создание лицензионного соглашения, выбор инсталляционной директории, ярлыков, ключей реестра и другие параметры. Если изучить продуктов, легко обнаружить следующий функциональный «пробел»: инсталлятор не поддерживает файловые ассоциации, DLL-расширения, элементы управления.
Что касается доступных опций инсталлятора - можно указать профиль установки, в зависимости от привилегий текущего пользователя. Инсталлятор поддерживает локализацию, причем русский язык доступен «из коробки», остальное скачивается отдельно. Возможна автоматическая - тихая - инсталляция без запроса данных у пользователя, после установки - проверка целостности пакета или другие настраиваемые действия.
Как уже было упомянуто, возможна интеграция Excelsior с NSIS. Excelsior Installer, по сути, выступает полноценным GUI для NSIS, настройки проекта экспортируются без проблем.
В ряду с этим участником обзора, стоит выделить еще один родственный продукт - Excelsior Delivery. По большей части функции Excelsior Installer дублируются. Но есть также и несколько дополнительных функций: добавление в систему OLE- и ActiveX-элементов, файловых ассоциаций, библиотек, создание опросов пользователей. Лицензионная версия Excelsior Delivery (стоимостью $99) позволяет также применить к установщику фирменное оформление (branding). Если эта опция неважна, можно скачать некоммерческую версию программы.
Резюме . Excelsior Installer - простая и очень понятная система для создания дистрибутивов, может использоваться как надстройка к NSIS. Обратная сторона медали - усредненная функциональность как Excelsior Installer, так и Delivery.
WiX Toolset
WiX (Windows Installer XML) - бесплатный набор инструментов для создания инсталляторов (Windows Installer) с использованием спецификации XML. Из особенностей: интерфейс командной строки, интеграция с IDE, автоматизация процессов, поддержка базовых и расширенная поддержка Windows Installer.
Ядро WiX составляют компилятор (candle), компоновщик (light), библиотекарь (lit), декомпилятор (dark), бутстраппер инсталляции (burn) и другие утилиты. С их помощью можно создавать пакеты инсталляции.msi, модули слияния.msm, патчей.msp.
Создание инсталлятора состоит из нескольких основных этапов: разработка сценария, его проверка, обработка препроцессором, компиляция и компоновка. Для сборки инсталлятора и автоматизации в целом используется платформа MSBuild. Автоматизация - одно из главных преимуществ WiX при работе с достаточно ресурсоемкими проектами.
Исходный код имеет формат XML (расширение файла wxs). Сценарий описывает все этапы установки, начиная с описания проекта заканчивая действиями после установки. Редактировать его можно в любом редакторе с поддержкой данного формата.
WiX радует своими интеграционными возможностями: WiX Toolset предоставляет интерфейс командной строки. Для работы с проектом в Visual Studio (модуль IntelliSense) потребуется расширение .
В затруднительных ситуациях или при отсутствии времени на изучение сценариев, хорошую службу окажет графическая оболочка . Ее основные преимущества - импорт существующих wxs-проектов, структурирование xml-данных с удобным чтением и навигацией. С помощью мастера также несложно создать инсталляционный файл с нуля. Причем это далеко не единственный подобный инструмент (см. ).
Резюме . В данном случае, многое решает спецификация XML. WiX дает возможность программистам оперировать исходными данными, не прибегая к графической оболочке. В состав WiX входят все необходимые инструменты, вдобавок к этому функциональность инсталлятора может быть улучшена за счет расширений.
Основные функции
- создание единого EXE;
- разбивка установщика на диски;
- несколько типов установки программ (полный, выборочный, минимальный);
- возможность деинсталляции;
- функции сжатия (deflate, bzip2, 7-Zip);
- сравнение информации о версии, замена файлов, которые используются во время установки инсталлятором;
- создание ярлыков в указанном месте;
- запароленные и зашифрованные установки;
- тихая инсталляция и удаление;
- создание реестровых записей, а также INI-файлов.
Достоинства и недостатки
Достоинства:
- бесплатное распространение;
- поддержка русского языка;
- удобный и понятный интерфейс в виде Мастера;
- интегрированный скриптовый движок на языке Pascal;
- возможность многоязычной установки.
Недостатки:
- ручное редактирование скриптов.
Альтернативы
Install Creator. Бесплатное приложение для создания собственных уникальных установщиков различных программ. Дает возможность применения пользовательских иконок, записи значений в реестре, автоматической установки шрифтов, скачивания данных с серверов.
Install Wizard Creator. Простая бесплатная программа, с помощью которой можно создавать инсталляторы приложений. Операция выполняется в несколько шагов: указание названия, добавление файлов, нажатие на кнопку.
Принципы работы
Чтобы создать для программы единый установочный файл, запустите Inno Setup, нажмите на кнопку «Файл», «Новый» и запустите Мастер.
Создание установочного файла
В следующем окне укажите основные данные о приложении: имя, версия, разработчик, домашняя страница и т. д.
Затем в специальное поле необходимо внести exe-файл, запускающий установленное приложение, а также добавить список, включающий все его компоненты и файлы.
Если существует файл лицензии, укажите в следующем окне путь к нему. Также есть возможность создать Readme.txt, написать сообщение либо оставить строки пустыми.
- имя установочного файла;
- место для размещения скомпилированного файла;
- ярлык инсталлятора.
В последнем окошке нужно оставить все, как есть, что позволит упростить скрипт инсталлятора.
После указания всех необходимых параметров программа создаст упаковщик приложения.
Файл приложения
Inno Setup поможет сделать полноценный профессиональный инсталлятор, который будет обладать необходимой защитой и рядом обязательных функций.