Inno Setup Copyright (C) 1997-2026 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Setup or Uninstall Info GetCmdTail function GetCmdTail: String;

Returns all command line parameters passed to Setup or Uninstall as a single string, including undocumented internal parameters used by Setup and Uninstall.

ParamStr

ParamCount function ParamCount: Integer;

Returns the number of command line parameters passed to Setup or Uninstall, excluding undocumented internal parameters used by Setup and Uninstall.

ParamStr
GetCmdTail

ParamStr function ParamStr(Index: Integer): String;

Returns the Index-th command line parameter passed to Setup or Uninstall, excluding undocumented internal parameters used by Setup and Uninstall.

Parameter number zero is the full file name with which Setup or Uninstall was started.

If Index is invalid, ParamStr returns an empty string.

ParamCount
GetCmdTail

ActiveLanguage function ActiveLanguage: String;

Returns the name of the active language.

CustomMessage function CustomMessage(const MsgName: String): String;

Returns the value of the [CustomMessages] entry with the specified name. If an entry with the specified name does not exist, an exception will be raised.

var
  S: String;
begin
  S := CustomMessage('CreateDesktopIcon');
  // S = 'Create a &desktop icon'

  S := FmtMessage(CustomMessage('NameAndVersion'), ['My Program', '1.0']);
  // S = 'My Program version 1.0'
end;
FmtMessage function FmtMessage(const S: String; const Args: array of String): String;

Formats the string S using the specified string arguments. A %1 in the format string will be replaced with the first value in the Args array; a %2 will be replaced with the second value; and so on. %% will be replaced with %.

If a %-specifier references a non-existing argument, it will be returned untouched. No exception will be raised.

var
  S: String;
begin
  S := FmtMessage('%1 version %2 will be installed.', ['My Program', '1.0']);
  // S = 'My Program version 1.0 will be installed.'

  S := FmtMessage(SetupMessage(msgNotOnThisPlatform), ['Windows 2000']);
  // S = 'This program will not run on Windows 2000.'
end;
SetupMessage function SetupMessage(const ID: TSetupMessageID): String;

Returns the value of the specified message.

TSetupMessageID is defined as:

'msg' + the message name. Example: SetupMessage(msgSetupAppTitle)

var
  S: String;
begin
  S := SetupMessage(msgButtonNext);
  // S now equals '&Next >'
end;
WizardDirValue function WizardDirValue: String;

Returns the current contents of the edit control on the Select Destination Location page of the wizard.

Unlike ExpandConstant('{app}'), this function will not fail if called after the wizard is shown but prior to the user selecting a directory. Rather, it will return the default directory name.

WizardGroupValue function WizardGroupValue: String;

Returns the current contents of the edit control on the Select Start Menu Folder page of the wizard.

Unlike ExpandConstant('{group}'), this function will not fail if called after the wizard is shown but prior to the user selecting a folder. Rather, it will return the default folder name.

WizardNoIcons function WizardNoIcons: Boolean;

Returns the current setting of the Don't create a Start Menu folder check box on the Select Start Menu Folder page of the wizard.

WizardSetupType function WizardSetupType(const Description: Boolean): String;

Returns the name or description of the setup type selected by the user.

WizardSelectedComponents function WizardSelectedComponents(const Descriptions: Boolean): String;

Returns a comma-separated list of names or descriptions of the components selected by the user.

WizardIsComponentSelected
WizardSelectComponents

WizardIsComponentSelected function WizardIsComponentSelected(const Components: String): Boolean;

Returns True if the specified component is selected. Multiple components may be specified in the same manner as in a Components parameter.

WizardSelectedComponents
WizardSelectComponents

begin
  if WizardIsComponentSelected('helpfiles') then
    // the 'helpfiles' component is selected
end;
WizardSelectedTasks function WizardSelectedTasks(const Descriptions: Boolean): String;

Returns a comma-separated list of names or descriptions of the tasks selected by the user.

WizardIsTaskSelected
WizardSelectTasks

WizardIsTaskSelected function WizardIsTaskSelected(const Tasks: String): Boolean;

Returns True if the specified task is selected. Multiple tasks may be specified in the same manner as in a Tasks parameter.

WizardSelectedTasks
WizardSelectTasks

begin
  if WizardIsTaskSelected('desktopicon') then
    // the 'desktopicon' task is selected
end;
WizardSilent function WizardSilent: Boolean;

Returns True if Setup is running silently, False otherwise.

IsUninstaller function IsUninstaller: Boolean;

Returns True if Uninstall is running as opposed to Setup, False otherwise.

UninstallSilent function UninstallSilent: Boolean;

Returns True if Uninstall is running silently, False otherwise.

CurrentFilename function CurrentFilename: String;

Returns the destination file name of the [Files] entry that is currently being processed. The returned name may include constants.

Do not attempt to call this function from outside a Check, BeforeInstall or AfterInstall event function belonging to a [Files] entry.

CurrentSourceFilename function CurrentSourceFilename: String;

Returns the source file name of the [Files] entry that is currently being processed. The returned name may include constants.

Do not attempt to call this function from outside a Check, BeforeInstall or AfterInstall event function belonging to a [Files] entry with the "external" flag.

ExpandConstant function ExpandConstant(const S: String): String;

Changes all constants in S to their values. For example, ExpandConstant('{srcexe}') is changed to the filename of Setup.

An exception will be raised if there was an error expanding the constants.

ExpandConstantEx function ExpandConstantEx(const S: String; const CustomConst, CustomValue: String): String;

Changes all constants in S to their values. Additionally, any constant equal to CustomConst will be changed to CustomValue.

An exception will be raised if there was an error expanding the constants.

GetPreviousData function GetPreviousData(const ValueName, DefaultValueData: String): String;

Gets a value that was previously stored using SetPreviousData.

SetPreviousData function SetPreviousData(const PreviousDataKey: Integer; const ValueName, ValueData: String): Boolean;

Sets a value that can be restored later using GetPreviousData. Call SetPreviousData inside a RegisterPreviousData event function, once per setting.

Terminated function Terminated: Boolean;

Returns True if Setup or Uninstall is terminating, False otherwise.

Debugging function Debugging: Boolean;

Returns True if Setup or Uninstall is being debugged by the Compiler IDE or another application, False otherwise.

Run-time debugger

RegisterExtraCloseApplicationsResource function RegisterExtraCloseApplicationsResource(const AFilename: String): Boolean;

Registers an extra file which Setup should check for being in-use. Call RegisterExtraCloseApplicationsResource inside a RegisterExtraCloseApplicationsResources event function, once per file. Ignores CloseApplicationsFilter. Returns True if successful.

This function used to have a DisableFsRedir parameter, which was removed in 7.0. Use ApplyPathRedirRulesForCurrentProcess instead to register a 64-bit file from a 32-bit installer, or vice versa.

RmSessionStarted function RmSessionStarted: Boolean;

Returns True if a Restart Manager session was started, False otherwise.

CloseApplications

GetWizardForm function GetWizardForm: TWizardForm;

Returns the WizardForm support object, or raises an internal error if the object has not yet been created.

WizardForm

GetUninstallProgressForm function GetUninstallProgressForm: TUninstallProgressForm;

Returns the UninstallProgressForm support object, or raises an internal error if the object has not yet been created.

UninstallProgressForm

Wizard Update WizardSelectComponents procedure WizardSelectComponents(const Components: String);

Selects the specified comma separated list of component names.

If a component name is prefixed with a "*" character, any child components will be selected as well (except for those that include the dontinheritcheck flag). If a component name is prefixed with a "!" character, the component will be deselected.

This function does not change the state of unspecified components. This function can change the state of specified components that include the fixed flag.

WizardSelectedComponents
WizardIsComponentSelected

begin
  WizardSelectComponents('!helpfiles');
  // the 'helpfiles' component is deselected
end;
WizardSelectTasks procedure WizardSelectTasks(const Tasks: String);

Selects the specified comma separated list of task names.

If a task name is prefixed with a "!" character, the task will be deselected.

This function does not change the state of unspecified tasks.

WizardSelectedTasks
WizardIsTaskSelected

begin
  WizardSelectTasks('!desktopicon');
  // the 'desktopicon' task is deselected
end;
WizardSetBackImage procedure WizardSetBackImage(const BackImages: TArrayOfGraphic; const Stretch, Center: Boolean; const Opacity: Byte);

Sets a wizard background image. If multiple images are specified, the best-fitting one will be selected. If no images are specified, any existing background image is cleared and the other function parameters are ignored.

If Stretch is True, the image will be stretched or shrunk if the image is larger or smaller than required. If Stretch is False and Center is True, the image will be centered in the wizard window if it is smaller than required, and clipped if it is larger than required. Otherwise, the image will be positioned in the upper-left corner in its original size.

See WizardBackImageFile for information about the recommended image size(s).

Opacity specifies the opacity of the image, from 0 (fully transparent) to 255 (fully opaque, so non-transparent).

Raises an exception if a custom wizard background is not already active. Custom wizard backgrounds can be activated by using WizardBackColor, WizardBackColorDynamicDark, WizardBackImageFile, or WizardBackImageFileDynamicDark.

To display a single image for the entire duration of Setup, do not use this function. Instead, set WizardBackImageFile and optionally WizardBackImageFileDynamicDark.

[Setup]
WizardStyle=modern dynamic
WizardBackColor=#f3f3f3
WizardBackColorDynamicDark=#202020

[Files]
; Replace the DestDir parameters with the following if you do not need the
; images available during uninstall:
; Flags: dontcopy noencryption
Source: "MyImageNormal.png"; DestDir: "{app}"
Source: "MyImageLarge.png"; DestDir: "{app}"

[Code]
; Show an image on the install page only
<event('CurStepChanged')>
procedure CurStepChanged_UpdateBackImage(CurStep: TSetupStep);
var
  PngImages: TArrayOfGraphic; 
begin
  if CurStep = ssInstall then begin
    SetLength(PngImages, 2);
    PngImages[0] := TPngImage.Create;
    PngImages[1] := TPngImage.Create;
    try
      ExtractTemporaryFile('MyImageNormal.png');
      PngImages[0].LoadFromFile(ExpandConstant('{tmp}\MyImageNormal.png'));
      ExtractTemporaryFile('MyImageLarge.png');
      PngImages[1].LoadFromFile(ExpandConstant('{tmp}\MyImageLarge.png'));
      WizardSetBackImage(PngImages, True, True, 150);
    finally
      PngImages[1].Free;
      PngImages[0].Free;
    end;
  end else if CurStep = ssPostInstall then
    WizardSetBackImage([], True, True, 150);
end;

; Show an image during uninstall
<event('InitializeUninstallProgressForm')>
procedure InitializeUninstallProgressForm_UpdateBackImage;
var
  PngImages: TArrayOfGraphic;
begin
  try
    SetLength(PngImages, 2);
    PngImages[0] := TPngImage.Create;
    PngImages[1] := TPngImage.Create;
    try
      PngImages[0].LoadFromFile(ExpandConstant('{app}\MyImageNormal.png'));
      PngImages[1].LoadFromFile(ExpandConstant('{app}\MyImageLarge.png'));
      WizardSetBackImage(PngImages, True, False, 150);
    finally
      PngImages[1].Free;
      PngImages[0].Free;
    end;
  except
    LogFmt('Could not enable background image: %s', [GetExceptionMessage]);
  end;
end; 

; See CodeClasses.iss for another example.
Exception Abort procedure Abort;

Escapes from the current execution path without reporting an error.

Abort raises a special "silent exception" which operates like any other exception, but does not display an error message to the end user.

Abort does not cause Setup or Uninstall to exit unless it's called from one of these event functions (or another function invoked by them):

InitializeSetup
InitializeWizard
CurStepChanged(ssInstall)

InitializeUninstall
CurUninstallStepChanged(usAppMutexCheck)
CurUninstallStepChanged(usUninstall)

PrepareToInstall

RaiseException procedure RaiseException(const Msg: String);

Raises an exception with the specified message.

begin
  RaiseException('Your message goes here');

  // The following line will not be executed because of the exception
  MsgBox('You will not see this.', mbInformation, MB_OK);
end;
GetExceptionMessage function GetExceptionMessage: String;

Returns the message associated with the current exception. This function should only be called from within an except section, or a function called from an except section.

Exception messages generally do not end in a period. Pass the result of this function to AddPeriod to add one.

var
  I: Integer;
begin
  I := 1;
  try
    // The following line will raise a "Division by zero" exception
    I := I div 0;
  except
    // Catch the exception, deal with it, and continue
    MsgBox('We caught this exception: ' + AddPeriod(GetExceptionMessage),
      mbError, MB_OK);
  end;
end;
ShowExceptionMessage procedure ShowExceptionMessage;

Shows the message associated with the current exception in a message box. This function should only be called from within an except section, or a function called from an except section.

If logging is enabled (via the /LOG command line parameter or the SetupLogging [Setup] section directive or the UninstallLogging [Setup] section directive or debugging from the Compiler IDE) the message will be recorded in the log file and/or in the Compiler IDE's "Debug Output" view in addition to being shown.

var
  I: Integer;
begin
  I := 1;
  try
    // The following line will raise a "Division by zero" exception
    I := I div 0;
  except
    // Catch the exception, show it, and continue
    ShowExceptionMessage;
  end;
end;
System IsAdmin function IsAdmin: Boolean;

Returns True if Setup/Uninstall is running with administrative privileges.

IsAdminInstallMode function IsAdminInstallMode: Boolean;

Returns True if Setup is running in administrative install mode or if Uninstall is running with administrative privileges.

IsWinDark function IsWinDark: Boolean;

Returns True if the system is running in dark mode.

The system's light or dark mode setting is checked only once, at startup.

IsDarkInstallMode

IsDarkInstallMode function IsDarkInstallMode: Boolean;

Returns True if Setup or Uninstall runs with a dark style.

Can return True even if IsWinDark returns False.

Cannot return True if HighContrastActive returns True.

IsWinDark
HighContrastActive

HighContrastActive function HighContrastActive: Boolean;

Returns True if the user's system is set to a high-contrast theme.

IsDarkInstallMode

GetWindowsVersion function GetWindowsVersion: Cardinal;

Returns the version number of Windows packed into a single integer. The upper 8 bits specify the major version; the following 8 bits specify the minor version; the lower 16 bits specify the build number. For example, this function will return $0A002800 on Windows 10 Version 1507, which is version 10.0.10240.

To retrieve just the major version number, use: "GetWindowsVersion shr 24". To retrieve just the minor version number, use: "(GetWindowsVersion shr 16) and $FF". To retrieve just the build number, use: "GetWindowsVersion and $FFFF".

function IsWindows8OrLater: Boolean;
begin
  Result := (GetWindowsVersion >= $06020000);
end;

GetWindowsVersionEx

GetWindowsVersionEx procedure GetWindowsVersionEx(var Version: TWindowsVersion);

Returns extended information about the version of Windows in a record.

TWindowsVersion is defined as:

  TWindowsVersion = record
    Major: Cardinal;             // Major version number
    Minor: Cardinal;             // Minor version number
    Build: Cardinal;             // Build number
    ServicePackMajor: Cardinal;  // Major version number of service pack
    ServicePackMinor: Cardinal;  // Minor version number of service pack
    NTPlatform: Boolean;         // True if an NT-based platform
    ProductType: Byte;           // Product type (see below)
    SuiteMask: Word;             // Product suites installed (see below)
  end;

The ProductType field can be one of the following values:

  VER_NT_WORKSTATION
  VER_NT_DOMAIN_CONTROLLER
  VER_NT_SERVER

It can also be zero if the product type could not be determined (unlikely). VER_NT_WORKSTATION indicates a non-server edition of Windows (e.g. Workstation, Professional, or Home).

The SuiteMask field can be a combination of the following values:

  VER_SUITE_BACKOFFICE
  VER_SUITE_BLADE
  VER_SUITE_DATACENTER
  VER_SUITE_ENTERPRISE
  VER_SUITE_EMBEDDEDNT
  VER_SUITE_PERSONAL
  VER_SUITE_SINGLEUSERTS
  VER_SUITE_SMALLBUSINESS
  VER_SUITE_SMALLBUSINESS_RESTRICTED
  VER_SUITE_TERMINAL

VER_SUITE_PERSONAL, for example, is set on Home edition of Windows XP, and VER_SUITE_BLADE is set on the Web edition of Windows Server 2003.

The following example demonstrates how you can disallow installation on certain editions of Windows, and check service pack levels on multiple operating system versions. (Neither of these things are possible with the MinVersion [Setup] section directive.)

function InitializeSetup: Boolean;
var
  Version: TWindowsVersion;
  S: String;
begin
  GetWindowsVersionEx(Version);

  // Disallow installation on Home edition of Windows
  if Version.SuiteMask and VER_SUITE_PERSONAL <> 0 then
  begin
    SuppressibleMsgBox('This program cannot be installed on a Home edition of Windows.',
      mbCriticalError, MB_OK, IDOK);
    Result := False;
    Exit;
  end;

  // Disallow installation on domain controllers
  if Version.ProductType = VER_NT_DOMAIN_CONTROLLER then
  begin
    SuppressibleMsgBox('This program cannot be installed on domain controllers.',
      mbCriticalError, MB_OK, IDOK);
    Result := False;
    Exit;
  end;

  Result := True;
end;
GetWindowsVersionString function GetWindowsVersionString: String;

Returns the version number of Windows in string form. On Windows 2000, for example, this function will return "5.00.2195".

IsWin64 function IsWin64: Boolean;

Returns True if the system is running a 64-bit version of Windows. If False is returned, you cannot utilize any of Inno Setup's 64-bit-only features.

Another way to describe this function is: Returns True if the system matches architecture identifier win64.

Do not use this function to detect 64-bit install mode, use Is64BitInstallMode instead.

begin
  // Check IsWin64 before using a 64-bit-only feature to
  // avoid an exception when running on 32-bit Windows.
  if IsWin64 then
  begin
    MsgBox('64-bit program files reside in: ' +
      ExpandConstant('{autopf64}'), mbInformation, MB_OK);
  end;
end;

Is64BitInstallMode
ProcessorArchitecture

Is64BitInstallMode function Is64BitInstallMode: Boolean;

Returns True if Setup or Uninstall is running in 64-bit install mode, or False if it is running in 32-bit install mode.

When True is returned, it is safe to assume that IsWin64 will also return True.

begin
  if Is64BitInstallMode then
    MsgBox('Installing in 64-bit mode', mbInformation, MB_OK)
  else
    MsgBox('Installing in 32-bit mode', mbInformation, MB_OK);
end;

IsWin64
ProcessorArchitecture

ProcessorArchitecture function ProcessorArchitecture: TSetupProcessorArchitecture;

Returns the architecture of the system's Windows installation.

TSetupProcessorArchitecture is an enumerated type, defined as:

TSetupProcessorArchitecture = (paUnknown, paX86, paX64, paArm32, paArm64);

paUnknown is returned if Setup/Uninstall does not recognize the architecture of the Windows installation. It can be assumed that an "unknown" architecture is at least capable of executing the architecture of Setup/Uninstall itself (see SetupArchitecture), or Setup/Uninstall wouldn't be running at all.

paArm32 is not a possible return value for this function because no version of Windows for 32-bit Arm processors had the ability to run x86 binaries. (An x86 emulator was first introduced in Arm64 Windows.)

var
  S: String;
begin
  case ProcessorArchitecture of
    paX86: S := 'x86';
    paX64: S := 'x64';
    paArm64: S := 'Arm64';
  else
    S := 'Unrecognized';
  end;
  MsgBox('Windows architecture: ' + S, mbInformation, MB_OK);
end;

Architecture Identifier Matchers like IsX64Compatible
Is64BitInstallMode

IsArm32Compatible function IsArm32Compatible: Boolean;

Returns True if the system matches architecture identifier arm32compatible.

Architecture Identifier Matchers like IsX64Compatible
ProcessorArchitecture

IsArm64 function IsArm64: Boolean;

Returns True if the system matches architecture identifier arm64.

Architecture Identifier Matchers like IsX64Compatible
ProcessorArchitecture

IsX64Compatible function IsX64Compatible: Boolean;

Returns True if the system matches architecture identifier x64compatible.

Architecture Identifier Matchers like IsX64Compatible
ProcessorArchitecture

IsX64OS function IsX64OS: Boolean;

Returns True if the system matches architecture identifier x64os.

Before Inno Setup 6.3, IsX64OS was named IsX64. The compiler still accepts IsX64 as an alias for IsX64OS, but will emit a deprecation warning when used.

Architecture Identifier Matchers like IsX64Compatible
ProcessorArchitecture

IsX86Compatible function IsX86Compatible: Boolean;

Returns True if the system matches architecture identifier x86compatible.

Architecture Identifier Matchers like IsX64Compatible
ProcessorArchitecture

IsX86OS function IsX86OS: Boolean;

Returns True if the system matches architecture identifier x86os.

Before Inno Setup 6.3, IsX86OS was named IsX86. The compiler still accepts IsX86 as an alias for IsX86OS.

Architecture Identifier Matchers like IsX64Compatible
ProcessorArchitecture

IsCurrentProcess64Bit function IsCurrentProcess64Bit: Boolean;

Returns True if Setup is built as a 64-bit x64 application, as specified by SetupArchitecture.

InstallOnThisVersion function InstallOnThisVersion(const MinVersion, OnlyBelowVersion: String): Boolean;

This function is deprecated. Returns True if an entry with the specified MinVersion and OnlyBelowVersion parameters should be installed. If an invalid version string is passed, an exception will be raised.

This function is provided for backward compatibility only, and may be removed in a future release. New scripts should use GetWindowsVersion or GetWindowsVersionEx instead.

Prior to Inno Setup 5.5.0, this function returned irInstall rather than a Boolean True value. irInstall is now defined as an alias for True.

// Old method, deprecated
function IsWindows8OrLater: Boolean;
begin
  Result := InstallOnThisVersion('0,6.2', '0,0');
end;

// New method
function IsWindows8OrLater: Boolean;
begin
  Result := (GetWindowsVersion >= $06020000);
end;

GetWindowsVersion
GetWindowsVersionEx

IsDotNetInstalled function IsDotNetInstalled(const MinVersion: TDotNetVersion; const MinServicePack: Cardinal): Boolean;

Returns True if the .NET Framework with the specified MinVersion and MinServicePack parameters is installed.

TDotNetVersion is defined as:

TDotNetVersion = (net11, net20, net30, net35, net4Client, net4Full, net45, net451, net452, net46, net461, net462, net47, net471, net472, net48, net481);

function InitializeSetup: Boolean;
begin
  Result := IsDotNetInstalled(net462, 0); //Returns True if .NET Framework version 4.6.2 is installed, or a compatible version such as 4.8.1
  if not Result then
    SuppressibleMsgBox(FmtMessage(SetupMessage(msgWinVersionTooLowError), ['.NET Framework', '4.6.2']), mbCriticalError, MB_OK, IDOK);
end;
IsMsiProductInstalled function IsMsiProductInstalled(const UpgradeCode: String; const PackedMinVersion: Int64): Boolean;

Returns True if a MSI product with the specified UpgradeCode and PackedMinVersion is installed.

If there are multiple products installed with the specified UpgradeCode only the version of the first product returned by the system is checked.

An exception will be raised if an error occurs.

function InitializeSetup: Boolean;
begin
  Result := IsMsiProductInstalled('{20400CF0-DE7C-327E-9AE4-F0F38D9085F8}', PackVersionComponents(12, 0, 0, 0)); //Returns True if Visual C++ 2013 Redistributable (x64) is installed
  if not Result then
    SuppressibleMsgBox(FmtMessage(SetupMessage(msgWinVersionTooLowError), ['Visual C++ 2013 Redistributable (x64)', '12.0']), mbCriticalError, MB_OK, IDOK);
end;
GetEnv function GetEnv(const EnvVar: String): String;

Gets the value of the specified environment variable.

GetUserNameString function GetUserNameString: String;

Retrieves the name of the user currently logged onto the system.

GetComputerNameString function GetComputerNameString: String;

Retrieves the name of the computer the Setup or Uninstall program is running on (as returned by the Windows GetComputerName function).

GetUILanguage function GetUILanguage: Integer;

Returns the language identifier (LANGID) of the current user's UI language, which is either the language of Windows itself, or in the case of a MUI edition of Windows, the user interface language chosen in Control Panel's Regional Options. Returns 0 if the function fails (unlikely).

Refer to the list of valid language identifiers on MSDN.

begin
  if GetUILanguage = $0409 then
  begin
    // UI language is English (United States)
  end;

  // You can use "and $3FF" to extract the primary language identifier
  if GetUILanguage and $3FF = $09 then
  begin
    // Matches any variant of English
  end;
end;
FontExists function FontExists(const FaceName: String): Boolean;

Returns True if a font with the specified face name is installed on the system.

FindWindowByClassName function FindWindowByClassName(const ClassName: String): HWND;

Retrieves a handle to the top-level window whose class name matches the specified string. This function does not search child windows, and does not perform a case-sensitive search. Returns 0 if no window is found.

FindWindowByWindowName function FindWindowByWindowName(const WindowName: String): HWND;

Retrieves a handle to the top-level window whose window name matches the specified string. This function does not search child windows, and does not perform a case-sensitive search. Returns 0 if no window is found.

SendMessage function SendMessage(const Wnd: HWND; const Msg: Cardinal; const WParam: WPARAM; const LParam: LPARAM): LRESULT;

Sends the specified message to the specified window. Does not return until the window procedure has processed the message.

PostMessage function PostMessage(const Wnd: HWND; const Msg: Cardinal; const WParam: WPARAM; const LParam: LPARAM): Boolean;

Posts the specified message to the specified window, returning immediately. Returns True if successful.

SendNotifyMessage function SendNotifyMessage(const Wnd: HWND; const Msg: Cardinal; const WParam: WPARAM; const LParam: LPARAM): Boolean;

Sends the specified message to the specified window without waiting for the message to be processed by the destination window procedure. Returns True if successful.

RegisterWindowMessage function RegisterWindowMessage(const Name: String): Cardinal;

The RegisterWindowMessage function defines a new window message that is guaranteed to be unique throughout the system. The returned message value can be used when calling the SendBroadcastMessage or PostBroadcastMessage function.

SendBroadcastMessage function SendBroadcastMessage(const Msg: Cardinal; const WParam: WPARAM; const LParam: LPARAM): LRESULT;

Sends the specified message to top-level windows in the system. Does not return until all window procedure have processed the message.
The specified message must be unique. Use RegisterWindowMessage to get such a message.

PostBroadcastMessage function PostBroadcastMessage(const Msg: Cardinal; const WParam: WPARAM; const LParam: LPARAM): Boolean;

Posts the specified message to top-level windows in the system, returning immediately.
The specified message must be unique. Use RegisterWindowMessage to get such a message.

SendBroadcastNotifyMessage function SendBroadcastNotifyMessage(const Msg: Cardinal; const WParam: WPARAM; const LParam: LPARAM): Boolean;
CreateMutex procedure CreateMutex(const Name: String);

Creates a mutex with the specified name.

CheckForMutexes function CheckForMutexes(Mutexes: String): Boolean;

Returns True if any of the mutexes in the comma-separated Mutexes string exist.

MakePendingFileRenameOperationsChecksum procedure MakePendingFileRenameOperationsChecksum: String;

Calculates a checksum of the current PendingFileRenameOperations registry value. The caller can use this checksum to determine if PendingFileRenameOperations or WININIT.INI was changed (perhaps by another program).

var
  ChecksumBefore, ChecksumAfter: String;
begin
  ChecksumBefore := MakePendingFileRenameOperationsChecksum;
  // ...run a program...
  ChecksumAfter := MakePendingFileRenameOperationsChecksum;
  if ChecksumAfter <> ChecksumBefore then
    // PendingFileRenameOperations or WININIT.INI changed
end;
CreateCallback function CreateCallback(Method: AnyMethod): NativeInt;

Allows you to perform direct callbacks from DLL functions (like Windows API functions) to functions in your script.

function SetTimer(hWnd: HWND; nIDEvent: UINT_PTR; uElapse: UINT; lpTimerFunc: NativeInt): UINT_PTR;
external 'SetTimer@user32.dll stdcall';

var
  TimerCount: Integer;

procedure MyTimerProc(Arg1: HWND; Arg2: UINT; Arg3: UINT_PTR; Arg4: DWORD);
begin
  Inc(TimerCount);
  WizardForm.BeveledLabel.Caption := ' Timer! ' + IntToStr(TimerCount);
  WizardForm.BeveledLabel.Visible := True;
end;

procedure InitializeWizard;
begin
  SetTimer(0, 0, 1000, CreateCallback(@MyTimerProc));
end;
UnloadDLL procedure UnloadDLL(Filename: String);

Unloads the specified DLL that was loaded by the [Code] section using an "external" keyword. This can be useful if you need to delete the DLL.

The case of the filename and any path name must exactly match that of the function import. You will need to expand any constants in the filename yourself before passing it to UnloadDLL.

If the function import used a "files:" prefix, prepend the value of the {tmp} constant to the filename (e.g. ExpandConstant('{tmp}\filename.dll')).

It's not recommended that you try this, but if you attempt to call a function in a DLL that has been unloaded, the DLL will be re-loaded.

procedure DllFunc; external 'DllFunc@{app}\MyDll.dll stdcall uninstallonly';

...

begin
  // Call DllFunc
  DllFunc;

  // Unload the DLL
  UnloadDLL(ExpandConstant('{app}\MyDll.dll'));

  // Now we can delete the DLL
  DeleteFile(ExpandConstant('{app}\MyDll.dll'));
end;
DLLGetLastError function DLLGetLastError(): LongInt;

Returns value the last error code had right after the most recent DLL function call you made. Useful after calling Windows API functions (if the function sets the last error code).

It's recommended to use this function instead of directly calling the GetLastError Windows API function since Setup or Uninstall makes API calls of its own, so the last error code could be overwritten at any time.

Refer to the system error codes on MSDN.

function MessageBox(hWnd: Integer; lpText, lpCaption: AnsiString; uType: Cardinal): Integer; external 'MessageBoxA@user32.dll stdcall';

...

begin
  if MessageBox(-1, '', '', -1) = 0 then
    MsgBox(SysErrorMessage(DLLGetLastError), mbError, mb_Ok);
String Chr function Chr(X: Word): Char;

Returns the character with the specified ordinal value.

Ord function Ord(X: Ordinal): UInt64;

Returns the ordinal value of the specified character, integer or enumeration value.

Copy function Copy(S: AnyString; Index, Count: Integer): String;

Returns a string containing Count characters starting at S[Index].
If Index is larger than the length of S, Copy returns an empty string.
If Count specifies more characters than are available, only the characters from S[Index] to the end of S are returned.

Length function Length(S: AnyString): LongInt;

Returns the length of the specified string.

LowerCase function LowerCase(S: AnyString): String;

Returns a copy of the string S, but with all 7-bit ASCII characters between 'A' and 'Z' converted to lowercase. To convert 8-bit international characters, use AnsiLowerCase instead.

UpperCase function UpperCase(S: AnyString): String;

Returns a copy of the string S, but with all 7-bit ASCII characters between 'a' and 'z' converted to uppercase. To convert 8-bit international characters, use AnsiUpperCase instead.

AnsiLowerCase function AnsiLowerCase(S: AnyString): String;

Returns a string that is a copy of the given string converted to lowercase. The conversion uses the current Windows locale. This function supports multi-byte character sets (MBCS).

AnsiUpperCase function AnsiUpperCase(S: AnyString): String;

Returns a string that is a copy of the given string converted to uppercase. The conversion uses the current Windows locale. This function supports multi-byte character sets (MBCS).

StringOfChar function StringOfChar(C: Char; I : LongInt): String;

Returns a string of length I with all characters set to character C.

Delete procedure Delete(var S: AnyString; Index, Count: Integer);

Removes a substring of Count characters from string S starting at S[Index].
If Index is larger than the length of S, no characters are deleted. If Count specifies more characters than remain starting at the S[Index], Delete removes the rest of the string.

Insert procedure Insert(Source: AnyString; var Dest: AnyString; Index: Integer);

Merges Source into Dest at the position Dest[Index].

StringChange function StringChange(var S: String; const FromStr, ToStr: String): Integer;

This function is deprecated. It is equivalent to calling StringChangeEx with the SupportMBCS parameter set to False.

StringChangeEx function StringChangeEx(var S: String; const FromStr, ToStr: String; const SupportDBCS: Boolean): Integer;

Changes all occurrences in S of FromStr to ToStr. If SupportDBCS is True (recommended unless you require binary safety), double-byte character sequences in S are recognized and handled properly. Otherwise, the function behaves in a binary-safe manner. Returns the number of times FromStr was matched and changed.

When working with strings containing paths or filenames, be sure to pass True in the SupportDBCS parameter. Otherwise, paths with Chinese, Japanese, or Korean characters may be corrupted.

var
  S: String;
begin
  S := ExpandConstant('{commonappdata}');
  // S = 'C:\Documents and Settings\All Users\Application Data'

  StringChangeEx(S, '\', '/', True);
  // S = 'C:/Documents and Settings/All Users/Application Data'
end;
Pos function Pos(SubStr, S: AnyString): Integer;

Searches for SubStr within S and returns the first index of SubStr within S, 1-based. If SubStr is not found, Pos returns zero. The Pos function is case-sensitive.

RPos

RPos function RPos(SubStr, S: String): Integer;

Searches for SubStr within S and returns the last index of SubStr within S, 1-based. If SubStr is not found, RPos returns zero. The RPos function is case-sensitive.

Pos

AddQuotes function AddQuotes(const S: String): String;

Adds a quote (") character to the left and right sides of the string if the string contains a space and it didn't have quotes already. This is primarily used when spawning another process with a long filename as one of the parameters.

RemoveQuotes function RemoveQuotes(const S: String): String;

Opposite of AddQuotes; removes any quotes around the string.

ConvertPercentStr function ConvertPercentStr(var S: String): Boolean;

Expands all %-encoded characters in the string (see RFC 2396). Returns True if all were successfully expanded.

CompareText function CompareText(const S1, S2: String): Integer;

Compares the strings S1 and S2 and returns 0 if they are equal. If S1 is greater than S2, CompareText returns an integer greater than 0. If S1 is less than S2, CompareText returns an integer less than 0. The CompareText function is not case-sensitive.

CompareStr function CompareStr(const S1, S2: String): Integer;

Compares S1 to S2, with case-sensitivity. The return value is less than 0 if S1 is less than S2, 0 if S1 equals S2, or greater than 0 if S1 is greater than S2.

SameText function SameText(const S1, S2: String): Boolean;

Compares the strings S1 and S2 and returns True if they are equal. The SameText function is not case-sensitive.

SameStr function SameStr(const S1, S2: String): Boolean;

Compares S1 to S2, with case-sensitivity. The return value is True if they are equal.

IsWildcard function IsWildcard(const Pattern: String): Boolean;

Returns True if the specified pattern contains a wildcard.

WildcardMatch function WildcardMatch(const Text, Pattern: String): Boolean;

Returns True if the specified text matches the specified pattern.

Format function Format(const Format: String; const Args: array of const): String;

Formats the string Format using the series of arguments in the open array Args. Formatting is controlled by the format string Format; the results are returned as a string.

An exception will be raised if an invalid format string is specified, too few arguments are passed, or if any arguments are of the wrong type.

var
  S: String;
  I: Integer;
begin
  S := Format('%d files found', [10]);
  // S = '10 files found'

  S := Format('Filename: %s', ['file.txt']);
  // S = 'Filename: file.txt'

  I := 64;
  S := Format('%d in hex, padded to 8 digits: %.8x', [I, I]);
  // S = '64 in hex, padded to 8 digits: 00000040'
end;
Trim function Trim(const S: AnyString): AnyString;

Trims leading and trailing spaces and control characters from the given string S.

TrimLeft function TrimLeft(const S: String): String;

Trims leading spaces and control characters from the given string S.

TrimRight function TrimRight(const S: String): String;

Trims trailing spaces and control characters from the given string S.

StringJoin function StringJoin(const Separator: String; const Values: TArrayOfString): String;

Joins two or more strings together separated by the given separator.

var
  S: String;
begin
  S := StringJoin(',', ['1', '2']);
  // S = '1,2'
end;

StringSplit

StringSplit function StringSplit(const S: String; const Separators: TArrayOfString; const Typ: TSplitType): TArrayOfString;

Splits the given string into substrings, using the given characters or strings to be used as separator. Empty substrings can be ignored.

TSplitType is defined as:

TSplitType = (stAll, stExcludeEmpty, stExcludeLastEmpty);

var
  A: array of String;
begin
  A := StringSplit('1,,2', [','], stExcludeEmpty);
  // A = ['1','2']
end;

StringJoin
StringSplitEx

StringSplitEx function StringSplitEx(const S: String; const Separators: TArrayOfString; const Quote: Char; const Typ: TSplitType): TArrayOfString;

Splits the given string into substrings, using the given characters or strings to be used as separator. Empty substrings can be ignored. Use the Quote parameter to specify the start and end character of a quoted part of the string where separators are ignored.

TSplitType is defined as:

TSplitType = (stAll, stExcludeEmpty, stExcludeLastEmpty);

var
  A: array of String;
begin
  A := StringSplitEx('1,",",2', [','], '"', stAll);
  // A = ['1','","','2']
end;

StringSplit

StrToIntDef function StrToIntDef(S: String; Def: LongInt): LongInt;

The StrToInt function converts the string passed in S into a number. If S does not represent a valid number, StrToInt returns the number passed in Def.

StrToInt function StrToInt(S: String): LongInt;

The StrToInt function converts the string passed in S into a number. Returns -1 if not successful.

Use of StrToIntDef instead of StrToInt is recommended.

StrToInt64Def function StrToInt64Def(S: String; Def: Int64): Int64;

The StrToInt64Def function converts the string passed in S into a 64-bit number. If S does not represent a valid 64-bit number, StrToInt returns the 64-bit number passed in Def.

StrToInt64 function StrToInt64(S: String): Int64;

The StrToInt64 function converts the string passed in S into a 64-bit number. Raises an exception if not successful.

Use of StrToInt64Def instead of StrToInt64 is recommended.

StrToFloat function StrToFloat(S: String): Extended;

The StrToFloat function converts the string passed in S into a floating point number. The character used for the decimal point should always be a dot. Raises an exception if not successful.

StrToColor function StrToColor(S: String): TColor;

The StrToColor function converts the string passed in S, formatted as '#rrggbb', into a color. Raises an exception if not successful.

IntToStr function IntToStr(I: Int64): String;

The IntToStr function converts a 64-bit number into a string.

FloatToStr function FloatToStr(E: Extended): String;

The FloatToStr function converts a floating point number into a string. The character used for the decimal point will always be a dot.

CharLength function CharLength(const S: String; const Index: Integer): Integer;

Returns the length in characters of the character in the specified string at the specified index, which is currently always 1.

AddBackslash function AddBackslash(const S: String): String;

Returns the specified string with a trailing backslash added, unless the string is empty or already ends in a slash or backslash.

RemoveBackslashUnlessRoot function RemoveBackslashUnlessRoot(const S: String): String;

Returns the specified string with any trailing slashes/backslashes removed, unless the string specifies the root directory of a drive (e.g. "C:\" or "\"), in which case it leaves 1 slash.

RemoveBackslash function RemoveBackslash(const S: String): String;

Returns the specified string with any trailing slashes/backslashes removed.

Use of this function is discouraged; use RemoveBackslashUnlessRoot instead when working with file system paths.

PathCombine function PathCombine(const Dir, Filename: String): String;

Combines a directory and file name into a single path. If Filename is empty the result is an empty string. If Filename already starts with a drive letter or slash it is returned unchanged. Otherwise a single backslash is inserted between Dir and Filename when needed.

PathHasInvalidCharacters function PathHasInvalidCharacters(const S: String; const AllowDriveLetterColon: Boolean): Boolean;

Returns True if the specified string contains characters that are never allowed in paths, or characters and path components that are accepted by the system but might present a security problem (such as '..' and sometimes ':'). Set AllowDriveLetterColon to True when the first character may be a drive letter followed by a colon.

Extended-length paths that start with a "\\?\" prefix are rejected because the '?' is treated as an invalid character.

PathIsRooted function PathIsRooted(const Filename: String): Boolean;

Returns True if the specified path begins with a drive letter and colon, or a slash.

PathNormalizeSlashes function PathNormalizeSlashes(const S: String): String;

Returns specified string minus any superfluous slashes, and with any forward slashes converted to backslashes. Does not remove a double backslash at the beginning of the string, since that signifies a UNC path.

PathSame function PathSame(const S1, S2: String): Boolean;

Returns True if the specified strings (typically filenames) are equal. Uses a locale-independent "ordinal" comparison, which is important when comparing filenames/paths. Ignores case.

Does not consider an extended-length path and its normal version to be the same.

PathStartsWith function PathStartsWith(const S, AStartsWith: String; const IgnoreCase: Boolean): Boolean;

Returns True if S starts with (or is equal to) AStartsWith. Uses a locale-independent "ordinal" comparison, which is important when comparing filenames/paths. Optionally ignores case.

PathEndsWith

PathEndsWith function PathEndsWith(const S, AEndsWith: String; const IgnoreCase: Boolean): Boolean;

Returns True if S ends with (or is equal to) AEndsWith. Uses a locale-independent "ordinal" comparison, which is important when comparing filenames/paths. Optionally ignores case.

PathStartsWith

AddPeriod function AddPeriod(const S: String): String;

Returns the specified string with a trailing period added, unless the string is empty or already ends in a period or other punctuation mark.

ChangeFileExt function ChangeFileExt(const FileName, Extension: String): String;

Takes the file name passed in FileName and changes the extension of the file name to the extension passed in Extension.

ExtractFileExt function ExtractFileExt(const FileName: String): String;

Extracts the extension part of the given file name. The resulting string includes the period character that separates the name and extension parts. The resulting string is empty if the given filename has no extension.

ExtractFileDir function ExtractFileDir(const FileName: String): String;

Extracts the drive and directory parts of the given file name, excluding a trailing backslash (unless it is a root directory). The resulting string is empty if FileName contains no drive and directory parts.

ExtractFilePath

ExtractFilePath function ExtractFilePath(const FileName: String): String;

Extracts the drive and directory parts of the given file name, including a trailing backslash. The resulting string is the leftmost characters of FileName, up to and including the colon or backslash that separates the path information from the name and extension. The resulting string is empty if FileName contains no drive and directory parts.

ExtractFileDir

ExtractFileName function ExtractFileName(const FileName: String): String;

Extracts the name and extension parts of the given file name. The resulting string is the rightmost characters of FileName, starting with the first character after the colon or backslash that separates the path information from the name and extension. The resulting string is equal to FileName if FileName contains no drive and directory parts.

ExtractFileDrive function ExtractFileDrive(const FileName: String): String;

Returns a string containing the 'drive' portion of a fully qualified path name for the file passed in FileName. For file names with drive letters, the resulting string is in the form '<drive>:'. For file names with a UNC path the resulting string is in the form '\\<servername>\<sharename>'. If the given path contains neither style of path prefix, the result is an empty string.

ExtractRelativePath function ExtractRelativePath(const BaseName, DestName: String): String;

Converts a fully qualified path name into a relative path name. The DestName parameter specifies the file name (including path) to be converted. BaseName is the fully qualified name of the base directory to which the returned path name should be relative. BaseName may or may not include a file name, but it must include the final path delimiter.

ExtractRelativePath strips out common path directories and inserts '..\' for each level up from the BaseName.

var
  S: String;
begin
  S := ExtractRelativePath('c:\windows\system32\', 'c:\autoexec.bat');
  // S = ..\..\autoexec.bat
end;
ExpandFileName function ExpandFileName(const FileName: String): String;

Returns a string containing a fully qualified path name for the file passed in FileName. A fully qualified path name includes the drive letter and any directory and subdirectories in addition to the file name and extension.

An empty string is returned if the input is an empty string or contains only spaces.

An exception will be raised upon failure, which is only known to happen when the input or output path exceeds 32K characters.

ExpandUNCFileName function ExpandUNCFileName(const FileName: String): String;

Returns a string containing a fully qualified path name for the file passed in FileName. A fully qualified path name includes the drive portion of the filename in the UNC format '\\<servername>\<sharename>' if the drive letter is mapped to a network resource instead of a local drive and any directory and subdirectories in addition to the file name and extension.

PathConvertNormalToSuper function PathConvertNormalToSuper(const Filename: String; out SuperFilename: String; const Expand: Boolean): Boolean;

Converts a normal path to an extended-length path (also known as a super path). Set Expand to True unless you are sure that Filename is already an absolute (non-relative) path. Returns True if successful, False otherwise. Does not fail if the specified path already is an extended-length path.

ApplyPathRedirRules
PathConvertSuperToNormal

PathConvertSuperToNormal function PathConvertSuperToNormal(const FileName: String): String;

Converts an extended-length path (also known as a super path) to a normal path.

Only use this function in cases where an extended-length path is known to not work properly.

ApplyPathRedirRules
PathConvertNormalToSuper

GetDateTimeString function GetDateTimeString(const DateTimeFormat: String; const DateSeparator, TimeSeparator: Char): String;

Returns the current date and time as a string using the specified formatting. The following format specifiers are supported:

d Displays the day as a number without a leading zero (1-31).
dd Displays the day as a number with a leading zero (01-31).
ddd Displays the day as an abbreviation (Sun-Sat).
dddd Displays the day as a full name (Sunday-Saturday).
ddddd Displays the date using the system's short date format.
dddddd Displays the date using the system's long date format.
m Displays the month as a number without a leading zero (1-12).
If the m specifier immediately follows an h or hh specifier, the minute rather than the month is displayed.
mm Displays the month as a number with a leading zero (01-12).
If the mm specifier immediately follows an h or hh specifier, the minute rather than the month is displayed.
mmm Displays the month as an abbreviation (Jan-Dec).
mmmm Displays the month as a full name (January-December).
yy Displays the year as a two-digit number (00-99).
yyyy Displays the year as a four-digit number (0000-9999).
h Displays the hour without a leading zero (0-23).
hh Displays the hour with a leading zero (00-23).
n Displays the minute without a leading zero (0-59).
nn Displays the minute with a leading zero (00-59).
s Displays the second without a leading zero (0-59).
ss Displays the second with a leading zero (00-59).
t Displays the time using the system's short time format.
tt Displays the time using the system's long time format.
am/pm Uses the 12-hour clock for the preceding h or hh specifier.
Displays 'am' for any hour before noon, and 'pm' for any hour after noon.
The am/pm specifier can use lower, upper, or mixed case, and the result is displayed accordingly.
a/p Uses the 12-hour clock for the preceding h or hh specifier.
Displays 'a' for any hour before noon, and 'p' for any hour after noon.
The a/p specifier can use lower, upper, or mixed case, and the result is displayed accordingly.
/ Displays the date separator character given by the DateSeparator parameter.
If DateSeparator is set to #0, the system's date separator character will be used instead.
: Displays the time separator character given by the TimeSeparator parameter.
If TimeSeparator is set to #0, the system's time separator character will be used instead.
'xx'/"xx" Characters enclosed in single or double quotes are displayed as-is, and do not affect formatting.

Format specifiers may be written in upper case as well as in lower case letters--both produce the same result.

GetDateTimeString('ddddd', #0, #0);
GetDateTimeString('ddddd tt', #0, #0);
GetDateTimeString('dd/mm/yyyy hh:nn:ss', '-', ':');
SetLength procedure SetLength(var S: AnyString; L: LongInt);

Sets the length of a string.

CharToOemBuff procedure CharToOemBuff(var S: AnsiString);

Translates an ANSI string to a string with characters from the OEM-defined character set.

OemToCharBuff procedure OemToCharBuff(var S: AnsiString);

Translates a string with characters from the OEM-defined character set into an ANSI string.

Utf8Encode function Utf8Encode(const S: String): AnsiString;

Encodes a Unicode string into a UTF-8 encoded ANSI string.

Utf8Decode function Utf8Decode(const S: AnsiString): String;

Decodes a UTF-8 encoded ANSI string into a Unicode string.

GetMD5OfString function GetMD5OfString(const S: AnsiString): String;

Gets the MD5 sum of the specified string, as a string.

var
  MD5: String;
begin
  MD5 := GetMD5OfString('Test');
  // MD5 = '0cbc6611f5540bd0809a388dc95a615b'
end;
GetMD5OfUnicodeString function GetMD5OfUnicodeString(const S: String): String;

Gets the MD5 sum of the specified string, as a string.

var
  MD5: String;
begin
  MD5 := GetMD5OfUnicodeString('Test');
  // MD5 = '8e06915d5f5d4f8754f51892d884c477'
end;
GetSHA1OfString function GetSHA1OfString(const S: AnsiString): String;

Gets the SHA-1 hash of the specified string, as a string.

var
  SHA1: String;
begin
  SHA1 := GetSHA1OfString('Test');
  // SHA1 = '640ab2bae07bedc4c163f679a746f7ab7fb5d1fa'
end;
GetSHA1OfUnicodeString function GetSHA1OfUnicodeString(const S: String): String;

Gets the SHA-1 hash of the specified string, as a string.

var
  SHA1: String;
begin
  SHA1 := GetSHA1OfUnicodeString('Test');
  // SHA1 = '9ab696a37604d665dc97134dbee44cfe70451b1a'
end;
GetSHA256OfString function GetSHA256OfString(const S: AnsiString): String;

Gets the SHA-256 hash of the specified string, as a string.

var
  SHA256: String;
begin
  SHA256 := GetSHA256OfString('Test');
  // SHA256 = '532eaabd9574880dbf76b9b8cc00832c20a6ec113d682299550d7a6e0f345e25'
end;
GetSHA256OfUnicodeString function GetSHA256OfUnicodeString(const S: String): String;

Gets the SHA-256 hash of the specified string, as a string.

var
  SHA256: String;
begin
  SHA256 := GetSHA256OfUnicodeString('Test');
  // SHA256 = 'e6fa3ca87b1b641ab646d3b4933bba8d0970763f030b6578a60abdeae7366247'
end;
SysErrorMessage function SysErrorMessage(ErrorCode: Cardinal): String;

Returns a localized error message string that corresponds to the given operating system error code.

Refer to the system error codes on MSDN.

MinimizePathName function MinimizePathName(const Filename: String; const Font: TFont; MaxLen: Integer): String;

Returns a minimized filename that will not take more than MaxLen pixels to display with the given font. The minimizing is done by replacing the middle part with '...' as needed.

MyLabel.Caption := MinimizePathName(MyPathName, MyLabel.Font, MyLabel.Width);

TFont

Array GetArrayLength function GetArrayLength(var Arr: Array): LongInt;

Gets the length of an array.

SetArrayLength procedure SetArrayLength(var Arr: Array; I: LongInt);

Sets the length of an array. Always call SetArrayLength before accessing the elements in an array.

Stream GetSHA256OfStream function GetSHA256OfStream(const Stream: TStream): String;

Gets the SHA-256 hash of the specified stream, as a string. An exception will be raised upon failure.

GetSHA256OfFile

Variant Null function Null: Variant;

Returns a variant with a value of Null.

Unassigned function Unassigned: Variant;

Returns a variant with no value assigned.

VarIsEmpty function VarIsEmpty(const V: Variant): Boolean;

Returns True if the specified variant is unassigned.

VarIsClear

VarIsClear function VarIsClear(const V: Variant): Boolean;

Returns True if the specified variant's value is undefined.

VarIsEmpty

VarIsNull function VarIsNull(const V: Variant): Boolean;

Returns True if the specified variant has a value of Null assigned.

VarType function VarType(const V: Variant): TVarType;

Returns the type code of the specified variant.

The lower twelve bits of a variant type code (the bits defined by the varTypeMask bit mask) define the type of the variant. The varArray bit is set if the variant is an array of the given type. The varByRef bit is set if the variant is a reference to a value of the given type as opposed to an actual value.

The following variant type code constants are defined:

const
  varEmpty    = $0000;
  varNull     = $0001;
  varSmallInt = $0002;
  varInteger  = $0003;
  varSingle   = $0004;
  varDouble   = $0005;
  varCurrency = $0006;
  varDate     = $0007;
  varOleStr   = $0008;
  varDispatch = $0009;
  varError    = $000A;
  varBoolean  = $000B;
  varVariant  = $000C;
  varUnknown  = $000D;
  varByte     = $0011;
  varWord     = $0012;
  varLongWord = $0013;
  varInt64    = $0014;
  varStrArg   = $0048;
  varString   = $0100;
  varAny      = $0101;
  varUString  = $0102;
  varTypeMask = $0FFF;
  varArray    = $2000;
  varByRef    = $4000;
VarArrayGet function VarArrayGet(var S: Variant; I: Integer): Variant;

Returns the specified element of the specified variant array.

VarArraySet procedure VarArraySet(C: Variant; I: Integer; var S: Variant);

Sets the specified element of the specified variant array.

File System DirExists function DirExists(const Name: String): Boolean;

Returns True if the specified directory name exists. The specified name may include a trailing backslash.

FileExists function FileExists(const Name: String): Boolean;

Returns True if the specified file exists.

FileOrDirExists function FileOrDirExists(const Name: String): Boolean;

Returns True if the specified directory or file name exists. The specified name may include a trailing backslash.

FileSize function FileSize(const Name: String; var Size: Integer): Boolean;

Sets Size to the size of the specified file in bytes. Returns True if the file size was set successfully and False otherwise. Only supports file sizes smaller than 2 GB. To get all 64 bits of the file size, use FileSize64 instead.

FileSize64 function FileSize64(const Name: String; var Size: Int64): Boolean;

Sets Size to the size of the specified file in bytes. Returns True if the file size was set successfully and False otherwise.

GetSpaceOnDisk function GetSpaceOnDisk(const Path: String; const InMegabytes: Boolean; var Free, Total: Cardinal): Boolean;

Returns the number of free and total bytes or megabytes on a drive. Path specifies a directory on the drive or UNC share to check; it can be either the root (e.g. C:\) or an existing subdirectory. The setting of the InMegabytes parameter determines whether it returns figures in bytes or in megabytes (2^20), rounded down. Returns True if successful, False otherwise.

The figures returned by this function are capped at 2147483647 (2^31-1). Therefore, if InMegaBytes is False, it will return no more than 2147483647 bytes. If InMegaBytes is True, it will return no more than 2147483647 megabytes.

var
  Path: String;
  FreeMB, TotalMB: Cardinal;
begin
  // Get and display free megabytes on the Program Files drive
  Path := ExpandConstant('{autopf}');
  if GetSpaceOnDisk(Path, True, FreeMB, TotalMB) then
  begin
    MsgBox('There are ' + IntToStr(FreeMB) + ' megabytes free on ' +
      Path, mbInformation, MB_OK);
  end
  else begin
    // the function failed
  end;
end;

GetSpaceOnDisk64

GetSpaceOnDisk64 function GetSpaceOnDisk64(const Path: String; var Free, Total: Int64): Boolean;

Returns the number of free and total bytes on a drive. Path specifies a directory on the drive or UNC share to check; it can be either the root (e.g. C:\) or an existing subdirectory. Returns True if successful, False otherwise.

var
  Path: String;
  FreeBytes, TotalBytes: Int64;
begin
  // Get and display free bytes on the Program Files drive
  Path := ExpandConstant('{autopf}');
  if GetSpaceOnDisk64(Path, FreeBytes, TotalBytes) then
  begin
    MsgBox('There are ' + IntToStr(FreeBytes) + ' bytes free on ' +
      Path, mbInformation, MB_OK);
  end
  else begin
    // the function failed
  end;
end;

GetSpaceOnDisk

FileSearch function FileSearch(const Name, DirList: String): String;

Searches through the directories passed in DirList for a file named Name. DirList should be directory names separated by semicolons. If FileSearch locates a file matching Name, it returns a string containing a fully-qualified path name for that file. If no matching file exists, FileSearch returns an empty string.

FindFirst function FindFirst(const FileName: String; var FindRec: TFindRec): Boolean;

Retrieves information about the first file matching the wildcard specified by FileName. Returns True if successful.

TFindRec is defined as:

  TFindRec = record
    Name: String;               // name of the found file (no path)
    Attributes: LongWord;       // file attributes
    SizeHigh: LongWord;         // size of the file, upper 32 bits
    SizeLow: LongWord;          // size of the file, lower 32 bits
    CreationTime: TFileTime;    // time file was created
    LastAccessTime: TFileTime;  // time file was last accessed
    LastWriteTime: TFileTime;   // time file was last modified
    AlternateName: String;      // file's short name (empty if none)
    FindHandle: THandle;        // used internally
  end;

TFileTime is defined as:

  TFileTime = record
    dwLowDateTime: DWORD;
    dwHighDateTime: DWORD;
  end;

Valid file attributes are:

  FILE_ATTRIBUTE_READONLY
  FILE_ATTRIBUTE_HIDDEN
  FILE_ATTRIBUTE_SYSTEM
  FILE_ATTRIBUTE_DIRECTORY
  FILE_ATTRIBUTE_ARCHIVE
  FILE_ATTRIBUTE_DEVICE
  FILE_ATTRIBUTE_NORMAL
  FILE_ATTRIBUTE_TEMPORARY
  FILE_ATTRIBUTE_SPARSE_FILE
  FILE_ATTRIBUTE_REPARSE_POINT
  FILE_ATTRIBUTE_COMPRESSED
  FILE_ATTRIBUTE_OFFLINE
  FILE_ATTRIBUTE_NOT_CONTENT_INDEXED
  FILE_ATTRIBUTE_ENCRYPTED

If FindFirst returns True, call FindNext to enumerate the rest of the files, and then FindClose.

The following example counts the number of files in the Windows System directory.

var
  FilesFound: Integer;
  FindRec: TFindRec;
begin
  FilesFound := 0;
  if FindFirst(ExpandConstant('{sys}\*'), FindRec) then begin
    try
      repeat
        // Don't count directories
        if FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY = 0 then
          FilesFound := FilesFound + 1;
      until not FindNext(FindRec);
    finally
      FindClose(FindRec);
    end;
  end;
  MsgBox(IntToStr(FilesFound) + ' files found in the System directory.',
    mbInformation, MB_OK);
end;

FindNext
FindClose

FindNext function FindNext(var FindRec: TFindRec): Boolean;

Retrieves information about the next matching file after a call to FindFirst. Returns True if successful.

For an example, see the documentation for FindFirst.

FindFirst
FindClose

FindClose procedure FindClose(var FindRec: TFindRec);

Ends a find sequence, and frees the resources associated with it. You should always call this when FindFirst returns True.

For an example, see the documentation for FindFirst.

FindFirst
FindNext

GetCurrentDir function GetCurrentDir: String;

Returns a string containing the name of the current directory.

SetCurrentDir function SetCurrentDir(const Dir: String): Boolean;

Sets the current directory. The return value is True if the current directory was successfully changed, or False if an error occurred.

GetWinDir function GetWinDir: String;

Returns fully qualified path of the Windows directory. Only includes a trailing backslash if the Windows directory is the root directory.

GetSystemDir function GetSystemDir: String;

Returns fully qualified path of the Windows System directory. Only includes a trailing backslash if the Windows System directory is the root directory.

GetSysWow64Dir function GetSysWow64Dir: String;

64-bit Windows only: returns fully qualified path of the SysWOW64 directory. This is the actual directory in which 32-bit system files reside. An empty string is returned if this function is called on 32-bit Windows, or if for some reason it fails to retrieve the path on 64-bit Windows (unlikely).

var
  S: String;
begin
  S := GetSysWow64Dir;
  // Must check the result -- an empty string is returned
  // if there is no SysWOW64 directory.
  if S <> '' then
    MsgBox('SysWOW64 directory: ' + S, mbInformation, MB_OK)
  else
    MsgBox('There is no SysWOW64 directory.', mbInformation, MB_OK);
end;
GetTempDir function GetTempDir: String;

Returns fully qualified path of the temporary directory, with trailing backslash. Uses the Win32 function GetTempPath2 if available, and GetTempPath otherwise.

GetShellFolderByCSIDL function GetShellFolderByCSIDL(const Folder: Integer; const Create: Boolean): String;

Gets the path of the specified shell folder. Folder specifies the value of a CSIDL constant (a complete list of which can be found in ShlObj.h). If Create is True, the folder will be created if it does not exist. On failure, an empty string is returned.

It is recommended that you always specify True in the Create parameter. Otherwise, the function may fail if the CSIDL value is valid but the directory does not currently exist. (This is a Windows issue.)

const
  CSIDL_MYPICTURES = $0027;

...

var
  Path: String;
begin
  Path := GetShellFolderByCSIDL(CSIDL_MYPICTURES, True);
  if Path <> '' then
  begin
    MsgBox('My Pictures path = ' + Path, mbInformation, MB_OK);
  end
  else
  begin
    // handle failure
  end;
end;
GetShortName function GetShortName(const LongName: String): String;

Returns the short version of the specified long filename. If the short version of the long filename is not found, the long filename is returned.

GenerateUniqueName function GenerateUniqueName(Path: String; const Extension: String): String;

Generates a unique filename for a file in the specified path with the specified extension.

IsProtectedSystemFile function IsProtectedSystemFile(const Filename: String): Boolean;

Returns True if the specified file is protected by Windows File Protection (and therefore can't be replaced).

ApplyPathRedirRulesForCurrentProcess function ApplyPathRedirRulesForCurrentProcess(const A64Bit: Boolean; const APath: String): String;

Calls ApplyPathRedirRules function with the current process as the target process.

ApplyPathRedirRules function ApplyPathRedirRules(const A64Bit: Boolean; const APath: String; const ATargetProcess64Bit: Boolean): String;

Rewrites paths containing System32 to achieve the same effect as disabling/enabling WOW64 file system redirection, without actually changing the redirection state. Additionally, rewrites paths containing Sysnative for 64-bit target processes to ensure access to 64-bit System32.

Before rewriting, the path is expanded using ExpandFileName and converted to an extended-length path (also known as a super path).

Does not rewrite paths that do not contain System32 or Sysnative. Also does not rewrite when the system is running a 32-bit version of Windows.

Path expansion and conversion to extended-length path always occurs.

Does not rewrite for certain combinations, such as 64-bit System32 for a 64-bit target process, because no rewriting (or redirection) is needed for the target process to access the intended path. The following table lists all combinations for which rewriting has an effect, and the result:

A64BitAPathATargetProcess64BitResultExplanation
TrueSystem32FalseSysnativeThe 32-bit target process needs to use the Sysnative alias to access 64-bit system files.
FalseSystem32TrueSysWOW64The 64-bit target process needs to use SysWOW64 to access 32-bit system files.
FalseSystem32FalseSysWOW64Helps the 32-bit target process avoid some exceptions that apply to System32 but not to SysWOW64.
Any valueSysnativeTrueSystem32The 64-bit target process needs to use System32 instead of the Sysnative alias to access 64-bit system files, because the Sysnative alias is only accessible to 32-bit processes.

ApplyPathRedirRulesForCurrentProcess
PathConvertSuperToNormal

EnableFsRedirection function EnableFsRedirection(const Enable: Boolean): Boolean;

Function removed in 7.0.

Use support function ApplyPathRedirRulesForCurrentProcess instead, or a 64-bit installer.

32-bit installers can also use {sysnative} instead.

Use support functions ExecWithNativeSysDir, ExecAndLogOutputWithNativeSysDir, or ExecAndCaptureOutputWithNativeSysDir to launch an executable located in the 64-bit System directory from a 32-bit installer.

File Exec function Exec(const Filename, Params, WorkingDir: String; const ShowCmd: Integer; const Wait: TExecWait; var ResultCode: Integer): Boolean;

Executes the specified executable or batch file, using the same credentials as Setup/Uninstall. The Wait parameter specifies whether the function should return immediately or wait until the launched process has terminated or is idle. Returns True if the specified file was executed successfully, False otherwise.

If True is returned and Wait is ewWaitUntilTerminated then ResultCode returns the exit code of the process.

If False is returned then ResultCode specifies the error that occurred. Use SysErrorMessage(ResultCode) to get a description of the error.

TExecWait is defined as:

TExecWait = (ewNoWait, ewWaitUntilTerminated, ewWaitUntilIdle);

Use the ShellExec function instead if you need to launch a file that is not an executable or batch file.

Do not include quotes in the Filename parameter; the function will add them automatically.

The WorkingDir parameter can be an empty string, in which case it will try to extract a pathname from the Filename parameter and use that as the initial current directory for the process. If no pathname was specified in Filename, a default directory will be used.

If you have a single string containing both a filename and parameters (e.g. a command line obtained from an UninstallString registry value), you need not separate them yourself; just pass '>' in the Filename parameter, and the full command line in the Params parameter. (Note that when this is done, the function's special platform-independent support for .bat and .cmd files is disabled; it simply passes the specified command line to CreateProcess without any processing.)

To execute a 64-bit System32 binary from a 32-bit installer, use {sysnative} or ApplyPathRedirRulesForCurrentProcess to rewrite the path. In a 64-bit installer the rewrite is not needed.

Can't be used to execute Setup itself until the installation has started.

Note: compared to ISPP's Exec the ShowCmd and Wait parameters are swapped!

var
  ResultCode: Integer;
begin
  // Launch Notepad and wait for it to terminate
  if Exec(ExpandConstant('{win}\notepad.exe'), '', '', SW_SHOWNORMAL,
     ewWaitUntilTerminated, ResultCode) then
  begin
    // handle success if necessary; ResultCode contains the exit code
  end
  else begin
    // handle failure if necessary; ResultCode contains the error code
  end;
end;

ExecAndCaptureOutput
ExecAndLogOutput
ExecAsOriginalUser
ExecWithNativeSysDir

ExecAsOriginalUser function ExecAsOriginalUser(const Filename, Params, WorkingDir: String; const ShowCmd: Integer; const Wait: TExecWait; var ResultCode: Integer): Boolean;

Executes the specified executable or batch file, using the (normally non-elevated) credentials of the user that started Setup initially. See Exec and the [Run] section flag runasoriginaluser for more information.

This function is not supported at uninstall time.

In very unusual failure cases (e.g. if the initial Setup process died unexpectedly), it is possible for this function to raise an exception instead of just returning False.

ShellExec function ShellExec(const Verb, Filename, Params, WorkingDir: String; const ShowCmd: Integer; const Wait: TExecWait; var ErrorCode: Integer): Boolean;

Opens the specified file or performs another action specified by Verb, using the same credentials as Setup/Uninstall. The filename can be an executable file, a document file, a folder, or a URL. Verb may be an empty string, in which case the default verb for the file type is used (usually "open"). The Wait parameter specifies whether the function should return immediately or wait until the launched process has terminated or is idle. Returns True if the specified file was opened successfully, False otherwise. If False is returned then ErrorCode specifies the error that occurred. Use SysErrorMessage(ErrorCode) to get a description of the error.

TExecWait is defined as:

TExecWait = (ewNoWait, ewWaitUntilTerminated, ewWaitUntilIdle);

Note that passing a Wait value other than ewNoWait will have no effect if a new process isn't spawned (for example, if the file is opened inside an already-running instance of the program that handles the file type).

Refer to the system error codes on MSDN.

Can't be used to execute Setup itself until the installation has started.

var
  ErrorCode: Integer;
begin
  if not ShellExec('', ExpandConstant('{app}\filename.rtf'),
     '', '', SW_SHOWNORMAL, ewNoWait, ErrorCode) then
  begin
    // handle failure if necessary
  end;
end;

ShellExecAsOriginalUser

ShellExecAsOriginalUser function ShellExecAsOriginalUser(const Verb, Filename, Params, WorkingDir: String; const ShowCmd: Integer; const Wait: TExecWait; var ErrorCode: Integer): Boolean;

Opens the specified file or performs another action specified by Verb, using the (normally non-elevated) credentials of the user that started Setup initially. See ShellExec and the [Run] section flag runasoriginaluser for more information.

This function is not supported at uninstall time.

In very unusual failure cases (e.g. if the initial Setup process died unexpectedly), it is possible for this function to raise an exception instead of just returning False.

Refer to the system error codes on MSDN.

ExecWithNativeSysDir function ExecWithNativeSysDir(const Filename, Params, WorkingDir: String; const ShowCmd: Integer; const Wait: TExecWait; var ResultCode: Integer): Boolean;

Use this function instead of Exec to launch an executable located in the 64-bit System directory from a 32-bit installer.

This function avoids the problem that Exec in a 32-bit installer can only launch such an executable using the Sysnative alias, while that alias is not available to 64-bit applications. To achieve this, the function temporarily disables WOW64 file system redirection.

On 32-bit Windows or in a 64-bit installer, this function is just an alias for Exec.

var
  ResultCode: Integer;
begin
  if IsWin64 then begin
    { This starts 32-bit cmd.exe in a 32-bit installer, and 64-bit cmd.exe in a 64-bit installer }
    Exec(ExpandConstant('{cmd}'), '', '', SW_SHOWNORMAL, ewNoWait, ResultCode);
    { This starts 64-bit cmd.exe in both a 32-bit installer and a 64-bit installer }
    ExecWithNativeSysDir(ExpandConstant('{cmd}'), '', '', SW_SHOWNORMAL, ewNoWait, ResultCode);
    { WRONG: This would also start 64-bit cmd.exe in a 32-bit installer, but it would use the Sysnative alias, which 64-bit cmd.exe cannot access } 
    // Exec(ApplyPathRedirRulesForCurrentProcess(True, ExpandConstant('{cmd}')), '', '', SW_SHOWNORMAL, ewNoWait, ResultCode);
  end;
ExtractTemporaryFile procedure ExtractTemporaryFile(const FileName: String);

Extracts the specified file from the [Files] section to a temporary directory. To find the location of the temporary directory, use ExpandConstant('{tmp}').

The extracted files are automatically deleted when Setup exits.

An exception will be raised if the file wasn't extracted successfully, if the file wasn't found, or if the file was found but couldn't be processed because of its MinVersion and/or OnlyBelowVersion parameters.

Use Flags: dontcopy noencryption in the [Files] section to tell Setup to skip the file during the normal file copying stage, and to ensure it can be extracted before the password is known.

Use Flags: noencryption in the [Files] section if encryption is enabled and you call the ExtractTemporaryFile function prior to the user entering the correct password.

When solid compression is enabled, be sure to list your temporary files at (or near) the top of the [Files] section. In order to extract an arbitrary file in a solid-compressed installation, Setup must first decompress all prior files (to a temporary buffer in memory). This can result in a substantial delay if a number of other files are listed above the specified file in the [Files] section.

ExtractTemporaryFiles
DownloadTemporaryFile

[Files]
Source: "Readme.txt"; Flags: dontcopy noencryption

[Code]
function InitializeSetup: Boolean;
var
  S: AnsiString;
begin
  // Show the contents of Readme.txt (non Unicode) in a message box
  ExtractTemporaryFile('Readme.txt');
  if LoadStringFromFile(ExpandConstant('{tmp}\Readme.txt'), S) then
  begin
    MsgBox(S, mbInformation, MB_OK);
  end;

  Result := True;
end;
ExtractTemporaryFiles function ExtractTemporaryFiles(const Pattern: String): Integer;

Extracts the files matching the wildcard specified by Pattern from the [Files] section to a temporary directory. Returns the number of extracted files. To find the location of the temporary directory, use ExpandConstant('{tmp}').

The extracted files are automatically deleted when Setup exits.

An exception will be raised if no files were extracted successfully, no files were found, or if files were found but none could be processed because of their MinVersion and/or OnlyBelowVersion parameters.

Use Flags: dontcopy noencryption in the [Files] section to tell Setup to skip the file during the normal file copying stage, and to ensure it can be extracted before the password is known.

When solid compression is enabled, be sure to list your temporary files at (or near) the top of the [Files] section. In order to extract an arbitrary file in a solid-compressed installation, Setup must first decompress all prior files (to a temporary buffer in memory). This can result in a substantial delay if a number of other files are listed above the specified file in the [Files] section.

ExtractTemporaryFile

[Files]
Source: "Readme.txt"; Flags: dontcopy noencryption
Source: "MyProg.exe"; DestDir: "{app}"
Source: "MyProg.chm"; DestDir: "{app}"

[Code]
function InitializeSetup: Boolean;
var
  S: AnsiString;
  ResultCode: Integer;
begin
  // Show the contents of Readme.txt (non Unicode) in a message box
  ExtractTemporaryFiles('{tmp}\Readme.txt');
  if LoadStringFromFile(ExpandConstant('{tmp}\Readme.txt'), S) then
  begin
    MsgBox(S, mbInformation, MB_OK);
  end;

  // Extract all MyProg files and launch it. Note how {app} is left unexpanded.
  ExtractTemporaryFiles('{app}\MyProg.*');
  ExecAsOriginalUser(ExpandConstant('{tmp}\')+'{app}\MyProg.exe', '', '',
    SW_SHOWNORMAL, ewWaitUntilTerminated, ResultCode);

  Result := True;
end;
DownloadTemporaryFile function DownloadTemporaryFile(const Url, BaseName, RequiredSHA256OfFile: String; const OnDownloadProgress: TOnDownloadProgress): Int64;

Downloads the file from the specified URL to a temporary directory using the specified name. To find the location of the temporary directory, use ExpandConstant('{tmp}').

If RequiredSHA256OfFile is set it will compare this to the SHA-256 of the downloaded file and raise an exception if the hashes don't match.

An exception will be raised if there was an error. Otherwise, returns the number of bytes downloaded. Returns 0 if RequiredSHA256OfFile is set and the file was already downloaded.

Supports HTTPS (but not expired or self-signed certificates) and HTTP. Redirects are automatically followed and proxy settings are automatically used. Safe to use from services.

For basic authentication use SetDownloadCredentials.

Set OnDownloadProgress to a function to be informed of progress, or nil otherwise.

TOnDownloadProgress is defined as:

TOnDownloadProgress = function(const Url, FileName: String; const Progress, ProgressMax: Int64): Boolean;

ProgressMax will be 0 if the file size is still unknown. Return True to allow the download to continue, False otherwise.

[Code]
function OnDownloadProgress(const Url, Filename: String; const Progress, ProgressMax: Int64): Boolean;
begin
  if ProgressMax <> 0 then
    Log(Format('  %d of %d bytes done.', [Progress, ProgressMax]))
  else
    Log(Format('  %d bytes done.', [Progress]));
  Result := True;
end;

function InitializeSetup: Boolean;
begin
  try
    DownloadTemporaryFile('https://jrsoftware.org/download.php/is.exe?dontcount=1', 'innosetup-latest.exe', '', @OnDownloadProgress);
    DownloadTemporaryFile('https://jrsoftware.org/download.php/iscrypt.dll?dontcount=1', 'ISCrypt.dll', '2f6294f9aa09f59a574b5dcd33be54e16b39377984f3d5658cda44950fa0f8fc', @OnDownloadProgress);
    Result := True;
  except
    Log(GetExceptionMessage);
    Result := False;
  end;
end;

See CodeDownloadFiles.iss for another example which uses CreateDownloadPage instead.

See DownloadFiles.iss for an example of file download using just a [Files] entry.

SetDownloadCredentials
DownloadTemporaryFileWithISSigVerify
DownloadTemporaryFileSize
DownloadTemporaryFileDate
CreateDownloadPage
ExtractTemporaryFile
ExtractArchive

DownloadTemporaryFileWithISSigVerify function DownloadTemporaryFileWithISSigVerify(const Url, ISSigUrl, BaseName: String; const AllowedKeysRuntimeIDs: TStringList; const OnDownloadProgress: TOnDownloadProgress): Int64;

Like DownloadTemporaryFile, but downloads an .issig signature file first from the specified second URL and uses it to verify the main file downloaded from the first URL.

If the second URL is an empty string, Setup will instead append ".issig" (without quotes) to the path portion of the first URL. It will then use the result as the URL to download the .issig signature file from.

Verification uses the specified allowed keys, looked up using [ISSigKeys] section parameter RuntimeID. To allow all keys set AllowedKeysRuntimeIDs to nil.

An exception will be raised if there was an error. Otherwise, returns the number of bytes downloaded for the main file from the first URL. Returns 0 if the main file was already downloaded and still verified.

DownloadTemporaryFile
.issig Signatures: Introduction
ISSigVerify

[Code]
function InitializeSetup: Boolean;
begin
  try
    DownloadTemporaryFileWithISSigVerify(
      'https://jrsoftware.org/download.php/myprog-extrareadmes.7z', '',
      'myprog-extrareadmes.7z', nil, nil);
    Result := True;
  except
    Log(GetExceptionMessage);
    Result := False;
  end;
end;
SetDownloadCredentials procedure SetDownloadCredentials(const User, Pass: String);

Sets the basic authentication username and password for all following downloads done by DownloadTemporaryFile, DownloadTemporaryFileWithISSigVerify, DownloadTemporaryFileSize, and DownloadTemporaryFileDate.

Specify an empty username or password to unset the username or password.

DownloadTemporaryFile
DownloadTemporaryFileWithISSigVerify
DownloadTemporaryFileSize
DownloadTemporaryFileDate

DownloadTemporaryFileSize function DownloadTemporaryFileSize(const Url): Int64;

Returns the size of the file from the specified URL, without downloading the file. If the server does not provide the size, -1 will be returned.

An exception will be raised if there was an error.

See DownloadTemporaryFile for other considerations.

DownloadTemporaryFileDate function DownloadTemporaryFileDate(const Url): String;

Returns the last modified date of the file from the specified URL, without downloading the file. If the server does not provide the last modified file date, '' will be returned.

An exception will be raised if there was an error.

See DownloadTemporaryFile for other considerations.

ExtractArchive procedure ExtractArchive(const ArchiveFileName, DestDir, Password: String; const FullPaths: Boolean; const OnExtractionProgress: TOnExtractionProgress);

Extracts the specified archive to the specified directory, with or without preserving full path names.

An exception will be raised if there was an error.

The supported archive formats, beyond .7z, and the support for password-protected and multi-volume archives, depend on the ArchiveExtraction [Setup] section directive.

To allow the extraction of archives with custom extensions, such as self-extracting archives, call MapArchiveExtensions.

Set OnExtractionProgress to a function to be informed of progress, or nil otherwise.

TOnExtractionProgress is defined as:

TOnExtractionProgress = function(const ArchiveName, FileName: String; const Progress, ProgressMax: Int64): Boolean;

Return True to allow the extraction to continue, False otherwise.

See DownloadFiles.iss for an example of archive extraction using just a [Files] entry.

CreateExtractionPage
MapArchiveExtensions
CreateDownloadPage
DownloadTemporaryFile
ExtractTemporaryFile

MapArchiveExtensions procedure MapArchiveExtensions(const DestExt, SourceExt: String);

Allows files with a specified destination extension, such as .exe, to be treated as if they have a different source extension, such as .7z, for extraction purposes.

An exception will be raised if there was an error.

Calls to this function are ignored if the ArchiveExtraction [Setup] section directive is set to basic. In this case files as always extracted as .7z, regardless of the extension.

ExtractArchive
CreateExtractionPage

[Files]
Source: "{src}\My7ZipSFX.exe; DestDir: "{app}"; Flags: external extractarchive recursesubdirs createallsubdirs ignoreversion

[Code]
function InitializeSetup: Boolean;
begin
  MapArchiveExtensions('.exe', '.7z');
end;
GetMD5OfFile function GetMD5OfFile(const Filename: String): String;

Gets the MD5 sum of the specified file, as a string. An exception will be raised upon failure.

GetSHA1OfFile function GetSHA1OfFile(const Filename: String): String;

Gets the SHA-1 hash of the specified file, as a string. An exception will be raised upon failure.

GetSHA256OfFile function GetSHA256OfFile(const Filename: String): String;

Gets the SHA-256 hash of the specified file, as a string. An exception will be raised upon failure.

GetSHA256OfStream

ISSigVerify function ISSigVerify(const AllowedKeysRuntimeIDs: TStringList; const Filename: String; const VerifyFilename: Boolean; const KeepOpen: Boolean): TFileStream;

Verifies the signature of the specified file using the specified allowed keys, looked up using [ISSigKeys] section parameter RuntimeID. To allow all keys set AllowedKeysRuntimeIDs to nil. An exception will be raised upon failure.

If VerifyFilename is set to False the verification allows signatures for a different filename. It is recommended that you only set it to False if you don't know the name the file had when the signature was created. The size and hash of the file must always match.

Returns a handle to the still open file if KeepOpen is set to True, nil otherwise. It is recommended that you always set it to True if you plan to use the file for anything after verification. Otherwise, you risk creating a Time-Of-Check to Time-Of-Use (TOCTOU) problem.

var
  F: TFileStream;
begin
  F := ISSigVerify([], Filename, True);
  try
    // Use file
  finally
    F.Free;
  end;
end;

.issig Signatures: Introduction
DownloadTemporaryFileWithISSigVerify

RenameFile function RenameFile(const OldName, NewName: String): Boolean;

Attempts to change the name of the file or directory specified by OldFile to NewFile. If the operation succeeds, RenameFile returns True. If it cannot rename the file (for example, if a file called NewName already exists), it returns False.

Can't be used to rename Setup itself until the installation has started.

CopyFile function CopyFile(const ExistingFile, NewFile: String; const FailIfExists: Boolean): Boolean;

Copies ExistingFile to NewFile, preserving time stamp and file attributes.
If FailIfExists is True it will fail if NewFile already exists, otherwise it will overwrite it.
Returns True if successful, False otherwise.

Files copied using CopyFile are not automatically uninstalled. Consider using a [Files] entry with the external flag set instead.

Can't be used to copy Setup itself until the installation has started.

DeleteFile function DeleteFile(const FileName: String): Boolean;

Erases the file named by FileName from the disk.
If the file cannot be deleted or does not exist, the function returns False.

DelayDeleteFile procedure DelayDeleteFile(const Filename: String; const Tries: Integer);

Attempts to delete Filename, retrying up to Tries times if the file is in use. It delays 250 msec between tries.

SetNTFSCompression function SetNTFSCompression(const FileOrDir: String; Compress: Boolean): Boolean;

Changes the NTFS compression state of a file or directory. Returns True if successful, False otherwise.

If a directory is specified, the compression state of any files present in the directory will not be changed.

LoadStringFromFile function LoadStringFromFile(const FileName: String; var S: AnsiString): Boolean;

Loads the specified binary or non Unicode text file into the specified string. Returns True if successful, False otherwise.

Use LoadStringFromLockedFile to load even if the file is already opened for writing by another program.

LoadStringsFromFile

LoadStringFromLockedFile function LoadStringFromLockedFile(const FileName: String; var S: AnsiString): Boolean;

Loads the specified binary or non Unicode text file into the specified string, even if the file is already opened for writing by another program. Returns True if successful, False otherwise.

LoadStringFromFile

LoadStringsFromFile function LoadStringsFromFile(const FileName: String; var S: TArrayOfString): Boolean;

Loads the specified text file into the specified string array. UTF-8 encoded files with or without a BOM are also supported. Returns True if successful, False otherwise.

Use LoadStringsFromLockedFile to load even if the file is already opened for writing by another program.

LoadStringFromFile

LoadStringsFromLockedFile function LoadStringsFromLockedFile(const FileName: String; var S: TArrayOfString): Boolean;

Loads the specified text file into the specified string array, even if the file is already opened for writing by another program. UTF-8 encoded files with or without a BOM are also supported. Returns True if successful, False otherwise.

LoadStringsFromFile

SaveStringToFile function SaveStringToFile(const FileName: String; const S: AnsiString; const Append: Boolean): Boolean;

Saves the specified string to the specified file. If Append is True and the specified file already exists, it will be appended to instead of overwritten. Returns True if successful, False otherwise.

This function does not automatically write a line break before or after the string. If Append is True and the existing file did not end in a line break, the function will effectively append to the existing last line. To avoid this you can put line break characters before and/or after your string:

SaveStringToFile('c:\filename.txt', #13#10 + 'the string' + #13#10, True);

SaveStringsToFile function SaveStringsToFile(const FileName: String; const S: TArrayOfString; const Append: Boolean): Boolean;

Saves the specified string array to the specified file with ASCII encoding. If Append is True and the specified file already exists, it will be appended to instead of overwritten. Returns True if successful, False otherwise.

SaveStringsToUTF8File
SaveStringsToUTF8FileWithoutBOM

SaveStringsToUTF8File function SaveStringsToUTF8File(const FileName: String; const S: TArrayOfString; const Append: Boolean): Boolean;

Saves the specified string array to the specified file with UTF-8 encoding with a BOM. If Append is True and the specified file already exists, it will be appended to instead of overwritten. Returns True if successful, False otherwise.

SaveStringsToFile
SaveStringsToUTF8FileWithoutBOM

SaveStringsToUTF8FileWithoutBOM function SaveStringsToUTF8FileWithoutBOM(const FileName: String; const S: TArrayOfString; const Append: Boolean): Boolean;

Saves the specified string array to the specified file with UTF-8 encoding without a BOM. If Append is True and the specified file already exists, it will be appended to instead of overwritten. Returns True if successful, False otherwise.

SaveStringsToFile
SaveStringsToUTF8File

CreateDir function CreateDir(const Dir: String): Boolean;

Creates a new directory. The return value is True if a new directory was successfully created, or False if an error occurred.

ForceDirectories function ForceDirectories(Dir: String): Boolean;

Creates all the directories along the specified directory path all at once. If the first directories in the path do exist, but the latter ones don't, ForceDirectories creates just the ones that don't exist. Returns True if successful, False otherwise.

RemoveDir function RemoveDir(const Dir: String): Boolean;

Deletes an existing empty directory. The return value is True if the empty directory was successfully deleted, or False if an error occurred.

DelTree function DelTree(const Path: String; const IsDir, DeleteFiles, DeleteSubdirsAlso: Boolean): Boolean;

Deletes the specified directory if IsDir is set to True, or files/directories matching a wildcard if IsDir is set to False. Returns True if it was able to successfully remove everything.

If DeleteFiles is set to True, files inside the specified directory will be deleted if IsDir is True, or files matching the specified wildcard (including those with hidden, system, and read-only attributes) will be deleted if IsDir is False.

If DeleteFiles and DeleteSubdirsAlso are both set to True, subdirectories (and their contents) will be deleted in addition to files.

This function will remove directories that are reparse points, but it will not recursively delete files/directories inside them.

begin
  // Delete the directory C:\Test and everything inside it
  DelTree('C:\Test', True, True, True);

  // Delete files matching C:\Test\*.tmp
  DelTree('C:\Test\*.tmp', False, True, False);

  // Delete all files and directories inside C:\Test
  // but leave the directory itself
  DelTree('C:\Test\*', False, True, True);
end;
CreateShellLink function CreateShellLink(const Filename, Description, ShortcutTo, Parameters, WorkingDir, IconFilename: String; const IconIndex, ShowCmd: Integer): String;

Creates a shortcut to a file or folder. Returns the resulting filename of the link, which may differ from Filename if it ended up creating a .pif file instead of a .lnk file. On failure, an exception will be raised.

Parameters:
Filename
Filename of the shortcut file to be created. This should be the full path and must end with ".lnk".
Description
Description of the link. This will be displayed on a supporting OS when the user hovers the mouse over the file or shows the properties.
ShortcutTo
Target file for the shortcut. This must be the full path to the file. Double quotation marks to surround the path will be added automatically.
Parameters
Parameters to pass to the target file of the shortcut. Parameters which may include spaces should have double quote marks surrounding them. e.g. ExpandConstant('"{app}\foo"')
WorkingDir
Working directory for the target file. This should be set to an absolute directory.
IconFilename
Path to file to supply the icon. If this is left as the empty string then the system default icon for the target file will be used.
IconIndex
Zero-based index of the icon.
ShowCmd
One of the SW_* constants

You will most likely want to remove this shortcut on uninstall. Do this by adding an entry to the UninstallDelete section.

CreateShellLink(
  ExpandConstant('{app}\config\Open licence database.lnk'),
  'Opens the licence database in SQLite',
  ExpandConstant('{app}\config\sqlite.exe'),
  ExpandConstant('"{app}\config\licences.db"'),
  ExpandConstant('{app}\config'),
  '',
  0,
  SW_SHOWNORMAL);
UnpinShellLink function UnpinShellLink(const Filename: String): Boolean;

Attempt to unpin the shortcut with the specified filename. Returns True if the shortcut was successfully removed from the list of pinned items and/or the taskbar, or if the shortcut was not pinned at all.

RegisterServer procedure RegisterServer(const Is64Bit: Boolean; const Filename: String; const FailCriticalErrors: Boolean);

Registers the DLL/OCX with the specified filename. If Is64Bit is True, the DLL/OCX will be loaded as a 64-bit image and registered in a 64-bit process. If FailCriticalErrors is True, the system will not display any critical-error-handler message boxes. Raises an exception if not successful.

begin
  // Register hhctrl.ocx located in the System directory.
  RegisterServer(Is64BitInstallMode, ExpandConstant('{sys}\hhctrl.ocx'), False);
end;

Because we specify Is64BitInstallMode in the first parameter, it will register the 64-bit OCX in the 64-bit System directory when Setup is running in 64-bit install mode. Otherwise, it will register the 32-bit OCX in the 32-bit System directory.

UnregisterServer function UnregisterServer(const Is64Bit: Boolean; const Filename: String; const FailCriticalErrors: Boolean): Boolean;

Unregisters the DLL/OCX with the specified filename. If Is64Bit is True, the DLL/OCX will be loaded as a 64-bit image and unregistered in a 64-bit process. If FailCriticalErrors is True, the system will not display any critical-error-handler message boxes. Returns True if successful, False otherwise.

RegisterTypeLibrary procedure RegisterTypeLibrary(const Is64Bit: Boolean; const Filename: String);

Registers the type library with the specified filename. If Is64Bit is True, the type library will be registered in a 64-bit process. Raises an exception if not successful.

begin
  // Register stdole2.tlb located in the System directory.
  RegisterTypeLibrary(Is64BitInstallMode, ExpandConstant('{sys}\stdole2.tlb'));
end;

Because we specify Is64BitInstallMode in the first parameter, it will register the 64-bit type library in the 64-bit System directory when Setup is running in 64-bit install mode. Otherwise, it will register the 32-bit type library in the 32-bit System directory.

UnregisterTypeLibrary function UnregisterTypeLibrary(const Is64Bit: Boolean; const Filename: String): Boolean

Unregisters the type library with the specified filename. If Is64Bit is True, the type library will be unregistered in a 64-bit process. Returns True if successful, False otherwise.

IncrementSharedCount procedure IncrementSharedCount(const Is64Bit: Boolean; const Filename: String; const AlreadyExisted: Boolean);

Increments or initializes the reference count for the specified file in the following registry key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SharedDLLs

64-bit versions of Windows have two separate SharedDLLs keys, one for 64-bit files and one for 32-bit files. If Is64Bit is True, the 64-bit SharedDLLs key will be updated, otherwise the 32-bit SharedDLLs key will be updated. The setting of this parameter should correspond to the bitness of the file; for example, if it is a 32-bit DLL located in the 32-bit System directory, you should specify False. You may also specify Is64BitInstallMode in which case it will use the current install mode to determine which key to open.

Pass True in the AlreadyExisted parameter if the file already exists; in this case the initial reference count for the file will be 2 if the value for the file doesn't already exist in the registry. (This behavior is in line with Microsoft's requirements.)

An exception will be raised if the registry key cannot be opened for write access.

DecrementSharedCount function DecrementSharedCount(const Is64Bit: Boolean; const Filename: String): Boolean;

Decrements the reference count for the specified file in the following registry key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SharedDLLs

64-bit versions of Windows have two separate SharedDLLs keys, one for 64-bit files and one for 32-bit files. If Is64Bit is True, the 64-bit SharedDLLs key will be updated, otherwise the 32-bit SharedDLLs key will be updated. The setting of this parameter should correspond to the bitness of the file; for example, if it is a 32-bit DLL located in the 32-bit System directory, you should specify False. You may also specify Is64BitInstallMode in which case it will use the current install mode to determine which key to open.

Returns True if the count reached zero (meaning it's OK to delete the file). Returns False if the new count is greater than zero, or if the value for the file doesn't exist or is in an unrecognizable format.

An exception will be raised if the registry key cannot be opened for write access.

RestartReplace procedure RestartReplace(const TempFile, DestFile: String);

Renames TempFile to DestFile the next time Windows is started. If DestFile already existed, it will be overwritten. If DestFile is '' then TempFile will be deleted. An exception will be raised upon failure.

UnregisterFont procedure UnregisterFont(const FontName, FontFilename: String; const PerUserFont: Boolean);

Unregisters the font with the specified face and filename.

ModifyPifFile function ModifyPifFile(const Filename: String; const CloseOnExit: Boolean): Boolean;

Changes the "Close on exit" setting of a .pif file. Returns True if it was able to make the change.

File Version GetVersionNumbers function GetVersionNumbers(const Filename: String; var VersionMS, VersionLS: Cardinal): Boolean;

Gets the version numbers of the specified file. Returns True if successful, False otherwise.

PackVersionNumbers

GetVersionComponents function GetVersionComponents(const Filename: String; var Major, Minor, Revision, Build: Word): Boolean;

Gets the individual version components of the specified file. Returns True if successful, False otherwise.

PackVersionComponents

GetVersionNumbersString function GetVersionNumbersString(const Filename: String; var Version: String): Boolean;

Gets the version of the specified file as a string (in "0.0.0.0" format). Returns True if successful, False otherwise.

GetPackedVersion function GetPackedVersion(const Filename: String; var Version: Int64): Boolean;

Gets the packed version of the specified file. Returns True if successful, False otherwise.

Always use ComparePackedVersion or SamePackedVersion to compare packed versions.

PackVersionComponents

PackVersionNumbers function PackVersionNumbers(const VersionMS, VersionLS: Cardinal): Int64;

Packs version numbers into a single value.

Always use ComparePackedVersion or SamePackedVersion to compare packed versions.

GetVersionNumbers
PackVersionComponents
UnpackVersionNumbers

PackVersionComponents function PackVersionComponents(const Major, Minor, Revision, Build: Word): Int64;

Packs individual version components into a single value.

Always use ComparePackedVersion or SamePackedVersion to compare packed versions.

GetVersionComponents
PackVersionNumbers
UnpackVersionComponents

ComparePackedVersion function ComparePackedVersion(const Version1, Version2: Int64): Integer;

Compares Version1 to Version2. The return value is less than 0 if Version1 is less than Version2, 0 if Version1 equals Version2, or greater than 0 if Version1 is greater than Version2.

SamePackedVersion function SamePackedVersion(const Version1, Version2: Int64): Boolean;

Compares the packed versions Version1 and Version2 and returns True if they are equal.

UnpackVersionNumbers procedure UnpackVersionNumbers(const Version: Int64; var VersionMS, VersionLS: Cardinal);

Unpacks a packed version into version numbers.

UnpackVersionComponents
PackVersionNumbers

UnpackVersionComponents procedure UnpackVersionComponents(const Version: Int64; var Major, Minor, Revision, Build: Word);

Unpacks a packed version into individual version components.

UnpackVersionNumbers
PackVersionComponents

VersionToStr function VersionToStr(const Version: Int64): String;

Returns the specified packed version as a string (in "0.0.0.0" format).

StrToVersion
UnpackVersionNumbers
UnpackVersionComponents

StrToVersion function StrToVersion(const Version: String; var Version: Int64): Boolean;

Returns the specified string (in "0.0.0.0" format) as a packed version. Returns True if successful, False otherwise.

VersionToStr
PackVersionNumbers
PackVersionComponents

Registry RegKeyExists function RegKeyExists(const RootKey: HKEY; const SubKeyName: String): Boolean;

Returns True if the specified registry key exists.

begin
  if RegKeyExists(HKEY_AUTO, 'Software\Jordan Russell\Inno Setup') then
  begin
    // The key exists
  end;
end;
RegValueExists function RegValueExists(const RootKey: HKEY; const SubKeyName, ValueName: String): Boolean;

Returns True if the specified registry key and value exist.

begin
  if RegValueExists(HKEY_CURRENT_USER, 'Console', 'WindowSize') then
  begin
    // The value exists
  end;
end;
RegGetSubkeyNames function RegGetSubkeyNames(const RootKey: HKEY; const SubKeyName: String; var Names: TArrayOfString): Boolean;

Opens the specified registry key and reads the names of its subkeys into the specified string array Names. Returns True if successful, False otherwise.

var
  Names: TArrayOfString;
  S: String;
begin
  if RegGetSubkeyNames(HKEY_CURRENT_USER, 'Control Panel', Names) then
  begin
    S := StringJoin(#13#10, Names);
    MsgBox('List of subkeys:'#13#10#13#10 + S, mbInformation, MB_OK);
  end else
  begin
    // add any code to handle failure here
  end;
end;
RegGetValueNames function RegGetValueNames(const RootKey: HKEY; const SubKeyName: String; var Names: TArrayOfString): Boolean;

Opens the specified registry key and reads the names of its values into the specified string array Names. Returns True if successful, False otherwise.

var
  Names: TArrayOfString;
  S: String;
begin
  if RegGetValueNames(HKEY_CURRENT_USER, 'Control Panel\Mouse', Names) then
  begin
    S := StringJoin(#13#10, Names);
    MsgBox('List of values:'#13#10#13#10 + S, mbInformation, MB_OK);
  end else
  begin
    // add any code to handle failure here
  end;
end;
RegQueryStringValue function RegQueryStringValue(const RootKey: HKEY; const SubKeyName, ValueName: String; var ResultStr: String): Boolean;

Queries the specified REG_SZ- or REG_EXPAND_SZ-type value, and returns the data in ResultStr. Returns True if successful. When False is returned, ResultStr is unmodified.

var
  Country: String;
begin
  if RegQueryStringValue(HKEY_CURRENT_USER, 'Control Panel\International',
     'sCountry', Country) then
  begin
    // Successfully read the value
    MsgBox('Your country: ' + Country, mbInformation, MB_OK);
  end;
end;
RegQueryMultiStringValue function RegQueryMultiStringValue(const RootKey: HKEY; const SubKeyName, ValueName: String; var ResultStr: String): Boolean;

Queries the specified REG_MULTI_SZ-type registry value, and returns the data in ResultStr. Returns True if successful. When False is returned, ResultStr is unmodified.

In a REG_MULTI_SZ-type value, each string is separated by a null character (#0).

RegQueryDWordValue function RegQueryDWordValue(const RootKey: HKEY; const SubKeyName, ValueName: String; var ResultDWord: Cardinal): Boolean;

Queries the specified REG_DWORD-type registry value, and returns the data in ResultDWord. Returns True if successful. When False is returned, ResultDWord is unmodified.

var
  HistoryBufferSize: Cardinal;
begin
  if RegQueryDWordValue(HKEY_CURRENT_USER, 'Console',
     'HistoryBufferSize', HistoryBufferSize) then
  begin
    // Successfully read the value
    MsgBox('Console history buffer size: ' + IntToStr(HistoryBufferSize),
      mbInformation, MB_OK);
  end;
end;
RegQueryBinaryValue function RegQueryBinaryValue(const RootKey: HKEY; const SubKeyName, ValueName: String; var ResultStr: AnsiString): Boolean;

Queries the specified registry value, and returns the data in ResultStr. Returns True if successful. When False is returned, ResultStr is unmodified.

RegWriteStringValue function RegWriteStringValue(const RootKey: HKEY; const SubKeyName, ValueName, Data: String): Boolean;

Writes the specified REG_SZ-type registry value. Returns True if successful, False otherwise.

If the value already exists and is of type REG_EXPAND_SZ, the new value will also be of type REG_EXPAND_SZ. Otherwise, a REG_SZ-type value will be created.

begin
  RegWriteStringValue(HKEY_AUTO, 'Software\My Company\My Program',
    'Language', ExpandConstant('{language}'));
end;
RegWriteExpandStringValue function RegWriteExpandStringValue(const RootKey: HKEY; const SubKeyName, ValueName, Data: String): Boolean;

Writes the specified REG_EXPAND_SZ-type registry value. Returns True if successful, False otherwise.

begin
  RegWriteStringValue(HKEY_CURRENT_USER, 'Software\My Company\My Program',
    'UserName', '%UserName%);
end;
RegWriteMultiStringValue function RegWriteMultiStringValue(const RootKey: HKEY; const SubKeyName, ValueName, Data: String): Boolean;

Writes the specified REG_MULTI_SZ-type registry value. Returns True if successful, False otherwise.

In a REG_MULTI_SZ-type value, each string is separated by a null character (#0).

begin
  RegWriteMultiStringValue(HKEY_AUTO, 'Software\My Company\My Program',
    'MultiStringTest', 'String1' + #0 + 'String2' + #0 + 'String3');
end;
RegWriteDWordValue function RegWriteDWordValue(const RootKey: HKEY; const SubKeyName, ValueName: String; const Data: Cardinal): Boolean;

Writes the specified REG_DWORD-type registry value. Returns True if successful, False otherwise.

begin
  RegWriteDWordValue(HKEY_AUTO, 'Software\My Company\My Program',
    'ShowToolbar', 1);
end;
RegWriteBinaryValue function RegWriteBinaryValue(const RootKey: HKEY; const SubKeyName, ValueName: String; const Data: AnsiString): Boolean;

Writes the specified REG_BINARY-type registry value. Returns True if successful, False otherwise.

begin
  RegWriteBinaryValue(HKEY_AUTO, 'Software\My Company\My Program',
    'BinaryTest', 'Whatever' + #1#2#3#4);
end;
RegDeleteKeyIncludingSubkeys function RegDeleteKeyIncludingSubkeys(const RootKey: HKEY; const SubkeyName: String): Boolean;

Deletes the specified key and all subkeys. Returns True if successful, False otherwise.

RegDeleteKeyIfEmpty function RegDeleteKeyIfEmpty(const RootKey: HKEY; const SubkeyName: String): Boolean;

Deletes the specified subkey if it has no subkeys or values. Returns True if successful, False otherwise.

RegDeleteValue function RegDeleteValue(const RootKey: HKEY; const SubKeyName, ValueName: String): Boolean;

Deletes the specified value. Returns True if successful, False otherwise.

INI File IniKeyExists function IniKeyExists(const Section, Key, Filename: String): Boolean;

Returns True if the specified INI key exists.

IsIniSectionEmpty function IsIniSectionEmpty(const Section, Filename: String): Boolean;

Returns True if the specified INI section is empty.

GetIniBool function GetIniBool(const Section, Key: String; const Default: Boolean; const Filename: String): Boolean

Reads a Boolean from an INI file.

GetIniInt function GetIniInt(const Section, Key: String; const Default, Min, Max: LongInt; const Filename: String): LongInt;

Reads a LongInt from an INI file. If the LongInt read is not between Min/Max then it returns Default. If Min=Max then Min/Max are ignored.

GetIniString function GetIniString(const Section, Key, Default, Filename: String): String;

Reads a String from an INI file.

SetIniBool function SetIniBool(const Section, Key: String; const Value: Boolean; const Filename: String): Boolean;

Writes a Boolean to an INI file.

SetIniInt function SetIniInt(const Section, Key: String; const Value: LongInt; const Filename: String): Boolean;

Writes a LongInt to an INI file.

SetIniString function SetIniString(const Section, Key, Value, Filename: String): Boolean;

Writes a string to an INI file.

DeleteIniSection procedure DeleteIniSection(const Section, Filename: String);

Deletes the specified section from an INI file.

DeleteIniEntry procedure DeleteIniEntry(const Section, Key, Filename: String);

Deletes the specified key from an INI file.

Custom Setup Wizard Page CreateInputQueryPage function CreateInputQueryPage(const AfterID: Integer; const ACaption, ADescription, ASubCaption: String): TInputQueryWizardPage;

Creates a wizard page containing edit boxes.

To create edit boxes on the page, call the Add method. Use the Values property to get/set the text of the edit boxes.

var
  Page: TInputQueryWizardPage;
  UserName, UserCompany: String;

...

// Create the page
Page := CreateInputQueryPage(wpWelcome,
  'Personal Information', 'Who are you?',
  'Please specify your name and the company for whom you work, then click Next.');

// Add items (False means it's not a password edit)
Page.Add('&Name:', False);
Page.Add('&Company:', False);

// Set initial values (optional)
Page.Values[0] := ExpandConstant('{sysuserinfoname}');
Page.Values[1] := ExpandConstant('{sysuserinfoorg}');

...

// Read values into variables
UserName := Page.Values[0];
UserCompany := Page.Values[1];

See AllPagesExample.iss for another example.

TInputQueryWizardPage

CreateInputOptionPage function CreateInputOptionPage(const AfterID: Integer; const ACaption, ADescription, ASubCaption: String; Exclusive, ListBox: Boolean): TInputOptionWizardPage;

Creates a wizard page containing check boxes or radio buttons.

If Exclusive is True, radio buttons are displayed instead of check boxes, and only one item in the list may be selected at a time. If ListBox is True, the check boxes or radio buttons are placed inside a scrollable list box.

To create check boxes / radio buttons on the page, call the Add method. Use the Values property to get/set the checked state of items. On pages created with Exclusive=True, you can get/set the index of the one selected item via the SelectedValueIndex property.

var
  Page: TInputOptionWizardPage;
  IsRegisteredUser: Boolean;

...

// Create the page
Page := CreateInputOptionPage(wpWelcome,
  'License Information', 'Are you a registered user?',
  'If you are a registered user, please check the box below, then click Next.',
  False, False);

// Add items
Page.Add('&I am a registered user');

// Set initial values (optional)
Page.Values[0] := False;

...

// Read values into variables
IsRegisteredUser := Page.Values[0];

See AllPagesExample.iss for another example.

TInputOptionWizardPage

CreateInputDirPage function CreateInputDirPage(const AfterID: Integer; const ACaption, ADescription, ASubCaption: String; AAppendDir: Boolean; ANewFolderName: String): TInputDirWizardPage;

Creates a wizard page that contains edit boxes and Browse buttons for selecting directories. If AAppendDir is True, the value of ANewFolderName will be appended onto any folder name the user clicks. If AAppendDir is False and ANewFolderName is not empty, a Make New Folder button will be shown that creates a new folder with the specified default name.

To create directory selection boxes on the page, call the Add method. Use the Values property to get/set the items' values.

var
  Page: TInputDirWizardPage;
  DataDir: String;

...

// Create the page
Page := CreateInputDirPage(wpWelcome,
  'Select Personal Data Location', 'Where should personal data files be stored?',
  'Personal data files will be stored in the following folder.'#13#10#13#10 +
  'To continue, click Next. If you would like to select a different folder, click Browse.',
  False, SetupMessage(msgNewFolderName));

// Add item (with an empty caption)
Page.Add('');

// Set initial value (optional)
Page.Values[0] := ExpandConstant('{userappdata}\My Company\My Program');

...

// Read value into variable
DataDir := Page.Values[0];

See AllPagesExample.iss for another example.

TInputDirWizardPage

CreateInputFilePage function CreateInputFilePage(const AfterID: Integer; const ACaption, ADescription, ASubCaption: String): TInputFileWizardPage;

Creates a wizard page that contains edit boxes and Browse buttons for selecting files.

To create file selection boxes on the page, call the Add method. Use the Values property to get/set the items' values.

An example Filter: 'Text files (*.txt)|*.txt|All files (*.*)|*.*'

var
  Page: TInputFileWizardPage;
  NotepadLocation: String;

...

// Create the page
Page := CreateInputFilePage(wpWelcome,
  'Select Notepad Location', 'Where is Notepad located?',
  'Select where Notepad is located, then click Next.');

// Add item
Page.Add('&Location of notepad.exe:',        // caption
  'Executable files|*.exe|All files|*.*',    // filters
  '.exe');                                   // default extension

// Set initial value (optional)
Page.Values[0] := ExpandConstant('{win}\notepad.exe');

...

// Read value into variable
NotepadLocation := Page.Values[0];

See AllPagesExample.iss for another example.

TInputFileWizardPage

CreateOutputMsgPage function CreateOutputMsgPage(const AfterID: Integer; const ACaption, ADescription, AMsg: String): TOutputMsgWizardPage;

Creates a wizard page containing only static text. The AMsg parameter specifies the text to display.

var
  Page: TOutputMsgWizardPage;

...

// Create the page
Page := CreateOutputMsgPage(wpWelcome,
  'Information', 'Please read the following important information before continuing.',
  'Blah blah blah.');

See AllPagesExample.iss for another example.

TOutputMsgWizardPage

CreateOutputMsgMemoPage function CreateOutputMsgMemoPage(const AfterID: Integer; const ACaption, ADescription, ASubCaption: String; const AMsg: AnsiString): TOutputMsgMemoWizardPage;

Creates a wizard page containing static text as well as a read-only, multi-line edit control, capable of displaying RTF text. The ASubCaption parameter specifies the static text to display. AMsg specifies the text to assign to the edit control.

var
  Page: TOutputMsgMemoWizardPage;

...

// Create the page
Page := CreateOutputMsgMemoPage(wpWelcome,
  'Information', 'Please read the following important information before continuing.',
  'When you are ready to continue with Setup, click Next.',
  'Blah blah blah.');

See AllPagesExample.iss for another example.

TOutputMsgMemoWizardPage

CreateOutputProgressPage function CreateOutputProgressPage(const ACaption, ADescription: String): TOutputProgressWizardPage;

Creates a wizard page containing static text as well as a progress bar (which is hidden by default).

Unlike the other types of wizard pages, progress pages are not displayed as part of the normal page sequence (note that there is no AfterID parameter). A progress page can only be displayed programmatically by calling its Show method.

Call the Show method to activate and show the page. When you're finished with it, call the Hide method to revert to the previous page.

Always put the Hide call inside the finally part of a try..finally language construct, as demonstrated in CodeDlg.iss. Not calling Hide will result in the wizard being permanently stuck on the progress page.

To set the text on the page, call the SetText method. SetText takes two string parameters: use the first to tell the user what you're doing, and the second to display a file or directory name. Either parameter may be blank.

To show or update the progress bar, call the SetProgress method. SetProgress takes two integer parameters: the first specifies the position of the progress bar (zero-based), and the second specifies the highest possible position. If the second parameter is 0, the progress bar will be hidden.

See CodeDlg.iss and AllPagesExample.iss example scrips in the "Examples" subdirectory in your Inno Setup directory for examples.

TOutputProgressWizardPage
CreateOutputMarqueeProgressPage

CreateOutputMarqueeProgressPage function CreateOutputMarqueeProgressPage(const ACaption, ADescription: String): TOutputMarqueeProgressWizardPage;

Creates a wizard page containing static text as well as a marquee progress bar.

See CreateOutputProgressPage for information on how to work with progress pages.

To animate the progress bar, call the Animate method. Do not call the SetProgress method, it will raise an internal error.

See AllPagesExample.iss for an example.

TOutputMarqueeProgressWizardPage

CreateDownloadPage function CreateDownloadPage(const ACaption, ADescription: String; const OnDownloadProgress: TOnDownloadProgress): TDownloadWizardPage;

Creates a wizard page to download files and show progress.

Set OnDownloadProgress to a function to be informed of progress, or nil otherwise.

Unlike the other types of wizard pages, progress pages are not displayed as part of the normal page sequence (note that there is no AfterID parameter). A progress page can only be displayed programmatically by calling its Show method.

Call the Show method to activate and show the page. When you're finished with it, call the Hide method to revert to the previous page.

Always put the Hide call inside the finally part of a try..finally language construct, as demonstrated in CodeDownloadFiles.iss. Not calling Hide will result in the wizard being permanently stuck on the progress page.

To add a new file to download, call the Add method. Always call the Clear method before adding the first file.

To start the download, call the Download method. An exception will be raised if there was an error. Otherwise, Download returns the number of bytes downloaded.

Set the ShowBaseNameInsteadOfUrl property to True to show the base name of the file which is being downloaded to the user instead of the URL.

See DownloadTemporaryFile for other considerations and the definition of TOnDownloadProgress.

See CodeDownloadFiles.iss for an example.

See DownloadFiles.iss for an example of file download using just a [Files] entry instead.

TDownloadWizardPage
DownloadTemporaryFile
CreateOutputProgressPage

CreateExtractionPage function CreateExtractionPage(const ACaption, ADescription: String; const OnExtractionProgress: TOnExtractionProgress): TExtractionWizardPage;

Creates a wizard page to extract archives and show progress.

The supported archive formats, beyond .7z, and the support for password-protected and multi-volume archives, depend on the ArchiveExtraction [Setup] section directive.

To allow the extraction of archives with custom extensions, such as self-extracting archives, call MapArchiveExtensions.

Set OnExtractionProgress to a function to be informed of progress, or nil otherwise.

Unlike the other types of wizard pages, progress pages are not displayed as part of the normal page sequence (note that there is no AfterID parameter). A progress page can only be displayed programmatically by calling its Show method.

Call the Show method to activate and show the page. When you're finished with it, call the Hide method to revert to the previous page.

Always put the Hide call inside the finally part of a try..finally language construct, as demonstrated in CodeDownloadFiles.iss. Not calling Hide will result in the wizard being permanently stuck on the progress page.

To add a new archive to extract, call the Add method or the AddEx method if the archive is password-protected. Always call the Clear method before adding the first file.

To start the extraction, call the Extract method. An exception will be raised if there was an error. Otherwise, Extract returns the number of archives extracted.

Set the ShowArchiveInsteadFile property to True to show the name of the archive which is being extracted to the user instead of the names of the files inside the archive.

See ExtractArchive for the definition of TOnExtractionProgress.

See CodeDownloadFiles.iss for an example of CreateDownloadPage which works very similar to CreateExtractionPage.

See DownloadFiles.iss for an example of archive extraction using just a [Files] entry instead.

TExtractionWizardPage
ExtractArchive
MapArchiveExtensions
CreateOutputProgressPage

CreateCustomPage function CreateCustomPage(const AfterID: Integer; const ACaption, ADescription: String): TWizardPage;

Creates a custom wizard page. The page is empty by default; you have to create your own controls afterward and place them on the page (by setting their Parent properties to the Surface property of the TWizardPage instance returned by this function).

See CodeClasses.iss and AllPagesExample.iss example scripts in the "Examples" subdirectory in your Inno Setup directory for examples.

TWizardPage

CreateCustomForm function CreateCustomForm(const ClientWidth, ClientHeight: Integer; const KeepSizeX, KeepSizeY: Boolean): TSetupForm;

Creates a form. The form is empty by default; you have to create your own controls afterward and place them on the form (by setting their Parent properties to the TSetupForm instance returned by this function).

You should call this function instead of creating TForm or TSetupForm instances directly. This function automatically initializes the font and other properties of the created form to be like Setup's other dialogs.

The [LangOptions] section's DialogFontName and DialogFontSize directives determine the font used by the form and, by default, any child controls created on the form.

You should use ScaleX and ScaleY to scale the desired client width and height to appropriate values. A form's client width and height are the form's full width and height minus its borders.

KeepSizeX and KeepSizeY specify whether the form is allowed to grow horizontally and vertically as the client area is resized, for [Setup] section directive WizardSizePercent.

The signature of the CreateCustomForm function has changed as of version 6.6.0. The width and height must now be specified upfront (they are now read-only properties once the form is constructed). Previously, your code might have looked like this:

  Form := CreateCustomForm;
  Form.Caption := 'TSetupForm';
  Form.ClientWidth := ScaleX(256);
  Form.ClientHeight := ScaleY(128);

Starting with version 6.6.0, it should be updated as follows:

  Form := CreateCustomForm(ScaleX(256), ScaleY(128), False, False);
  Form.Caption := 'TSetupForm';

The same applies to the KeepSizeX and KeepSizeY properties, which were writable properties before version 6.6.0, but are now specified as parameters when calling CreateCustomForm and are read-only properties afterwards.

See CodeClasses.iss for an example.

TForm
TSetupForm

PageFromID function PageFromID(const ID: Integer): TWizardPage;

Given a page ID, returns a TWizardPage instance. Call this if, for example, you need to get at the surface of a page and only know its ID.

An exception will be raised if an invalid page ID is specified.

var
  Page: TWizardPage;
begin
  Page := PageFromID(wpWelcome);
  Page.Surface.Color := clBlue;
end;

TWizardPage

PageIndexFromID function PageIndexFromID(const ID: Integer): NativeInt;

Given a page ID, returns an position index. Call this if, for example, you want to check whether a page is positioned before a certain other page.

function ShouldSkipPage(PageID: Integer): Boolean;
begin
  Result := PageIndexFromID(PageID) < PageIndexFromID(wpReady);
end;
ScaleX function ScaleX(X: Integer): Integer;

Takes an X coordinate or width and returns it scaled to fit the size of the current dialog font. If you use the default font settings with standard DPI (100%), then X is returned unchanged.

ScaleY function ScaleY(Y: Integer): Integer;

Takes a Y coordinate or height and returns it scaled to fit the size of the current dialog font. If you use the default font settings with standard DPI (100%), then Y is returned unchanged.

InitializeBitmapButtonFromIcon function InitializeBitmapButtonFromIcon(const BitmapButton: TBitmapButton; const IconFilename: String; const BkColor: TColor; const AscendingTrySizes: TArrayOfInteger): Boolean;

Initializes the given bitmap button with an icon from the given icon file using the given background color for transparent parts.

See InitializeBitmapImageFromIcon for more information.

InitializeBitmapImageFromIcon function InitializeBitmapImageFromIcon(const BitmapImage: TBitmapImage; const IconFilename: String; const BkColor: TColor; const AscendingTrySizes: TArrayOfInteger): Boolean;

Initializes the given bitmap image with an icon from the given icon file using the given background color for transparent parts.

The bitmap image should be scaled already and the function will load the largest fitting icon which has a size from the given array of sizes. After loading the function will set the size of the bitmap image to the loaded size.

The array must be sorted already from smallest to highest size.

If no match is found in the array (for example, because it is empty), the minimum of the bitmap image's width and height will be used as the size.

Returns True if the icon could be loaded, False otherwise.

procedure InitializeWizard;
var
  Page: TWizardPage;
  BitmapImage: TBitmapImage;
begin
  Page := CreateCustomPage(wpWelcome, 'Test', 'Test');

  BitmapImage := TBitmapImage.Create(Page);
  
  with BitmapImage do begin
    Width := ScaleX(32);
    Height := ScaleY(32);
    Parent := Page.Surface;
  end;

  InitializeBitmapImageFromIcon(BitmapImage, 'MyProg.ico', clNone, [32, 48, 64]);
end;

InitializeBitmapImageFromStockIcon

InitializeBitmapButtonFromStockIcon function InitializeBitmapButtonFromStockIcon(const BitmapButton: TBitmapButton; const Siid: Integer; const BkColor: TColor; const AscendingTrySizes: TArrayOfInteger): Boolean;

Initializes the given bitmap button with a system-defined stock icon from the given stock icon id (siid) using the given background color for transparent parts.

See InitializeBitmapImageFromStockIcon for more information.

InitializeBitmapImageFromStockIcon function InitializeBitmapImageFromStockIcon(const BitmapImage: TBitmapImage; const Siid: Integer; const BkColor: TColor; const AscendingTrySizes: TArrayOfInteger): Boolean;

Initializes the given bitmap image with a system-defined stock icon from the given stock icon id (siid) using the given background color for transparent parts.

The bitmap image should be scaled already and the function will load the largest fitting icon which has a size from the given array of sizes. After loading the function will set the size of the bitmap image to the loaded size.

The array must be sorted already from smallest to highest size.

If no match is found in the array (for example, because it is empty), the minimum of the bitmap image's width and height will be used as the size.

Unlike InitializeBitmapImageFromIcon, this function supports arbitrary sizes.

Returns True if the icon could be loaded, False otherwise.

See Microsoft Learn for an overview of all available icons.

Supported values for Siid are:

SIID_DOCNOASSOC, SIID_DOCASSOC, SIID_APPLICATION, SIID_FOLDER, SIID_FOLDEROPEN, SIID_DRIVE525, SIID_DRIVE35, SIID_DRIVEREMOVE, SIID_DRIVEFIXED, SIID_DRIVENET, SIID_DRIVENETDISABLED, SIID_DRIVECD, SIID_DRIVERAM, SIID_WORLD, SIID_SERVER, SIID_PRINTER, SIID_MYNETWORK, SIID_FIND, SIID_HELP, SIID_SHARE, SIID_LINK, SIID_SLOWFILE, SIID_RECYCLER, SIID_RECYCLERFULL, SIID_MEDIACDAUDIO, SIID_LOCK, SIID_AUTOLIST, SIID_PRINTERNET, SIID_SERVERSHARE, SIID_PRINTERFAX, SIID_PRINTERFAXNET, SIID_PRINTERFILE, SIID_STACK, SIID_MEDIASVCD, SIID_STUFFEDFOLDER, SIID_DRIVEUNKNOWN, SIID_DRIVEDVD, SIID_MEDIADVD, SIID_MEDIADVDRAM, SIID_MEDIADVDRW, SIID_MEDIADVDR, SIID_MEDIADVDROM, SIID_MEDIACDAUDIOPLUS, SIID_MEDIACDRW, SIID_MEDIACDR, SIID_MEDIACDBURN, SIID_MEDIABLANKCD, SIID_MEDIACDROM, SIID_AUDIOFILES, SIID_IMAGEFILES, SIID_VIDEOFILES, SIID_MIXEDFILES, SIID_FOLDERBACK, SIID_FOLDERFRONT, SIID_SHIELD, SIID_WARNING, SIID_INFO, SIID_ERROR, SIID_KEY, SIID_SOFTWARE, SIID_RENAME, SIID_DELETE, SIID_MEDIAAUDIODVD, SIID_MEDIAMOVIEDVD, SIID_MEDIAENHANCEDCD, SIID_MEDIAENHANCEDDVD, SIID_MEDIAHDDVD, SIID_MEDIABLURAY, SIID_MEDIAVCD, SIID_MEDIADVDPLUSR, SIID_MEDIADVDPLUSRW, SIID_DESKTOPPC, SIID_MOBILEPC, SIID_USERS, SIID_MEDIASMARTMEDIA, SIID_MEDIACOMPACTFLASH, SIID_DEVICECELLPHONE, SIID_DEVICECAMERA, SIID_DEVICEVIDEOCAMERA, SIID_DEVICEAUDIOPLAYER, SIID_NETWORKCONNECT, SIID_INTERNET, SIID_ZIPFILE, SIID_SETTINGS, SIID_DRIVEHDDVD, SIID_DRIVEBD, SIID_MEDIAHDDVDROM, SIID_MEDIAHDDVDR, SIID_MEDIAHDDVDRAM, SIID_MEDIABDROM, SIID_MEDIABDR, SIID_MEDIABDRE, SIID_CLUSTEREDDRIVE

procedure InitializeWizard;
var
  Page: TWizardPage;
  BitmapImage: TBitmapImage;
begin
  Page := CreateCustomPage(wpWelcome, 'Test', 'Test');

  BitmapImage := TBitmapImage.Create(Page);
  
  with BitmapImage do begin
    Width := ScaleX(32);
    Height := ScaleY(32);
    Parent := Page.Surface;
  end;

  InitializeBitmapImageFromStockIcon(BitmapImage, SIID_ERROR, clNone, [32, 48, 64]);
end;

InitializeBitmapImageFromIcon

Dialog MsgBox function MsgBox(const Text: String; const Typ: TMsgBoxType; const Buttons: Integer): Integer;

Displays a message box. Text specifies the message to display. Typ specifies which icon to display in the message box. Buttons specifies which buttons to include in the message box. Returns an ID* constant indicating the button the user clicked, or 0 if the function fails (which shouldn't happen unless an invalid parameter is specified or system resources are exhausted).

TMsgBoxType is defined as:

TMsgBoxType = (mbInformation, mbConfirmation, mbError, mbCriticalError);

Supported flags for Buttons are:

MB_OK, MB_OKCANCEL, MB_ABORTRETRYIGNORE, MB_YESNOCANCEL, MB_YESNO, MB_RETRYCANCEL, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON3, MB_SETFOREGROUND

Possible return values are:

IDOK, IDCANCEL, IDABORT, IDRETRY, IDIGNORE, IDYES, IDNO

begin
  // Display a simple message box with an OK button
  MsgBox('Hello.', mbInformation, MB_OK);

  // Ask the user a Yes/No question
  if MsgBox('Are you sure?', mbConfirmation, MB_YESNO) = IDYES then
  begin
    // user clicked Yes
  end;

  // Ask the user a Yes/No question, defaulting to No
  if MsgBox('Are you sure?', mbConfirmation, MB_YESNO or MB_DEFBUTTON2) = IDYES then
  begin
    // user clicked Yes
  end;
end;

SuppressibleMsgBox
TaskDialogMsgBox

SuppressibleMsgBox function SuppressibleMsgBox(const Text: String; const Typ: TMsgBoxType; const Buttons, Default: Integer): Integer;

Displays a suppressible message box. If message boxes are being suppressed (see Setup Command Line Parameters), Default is returned. Otherwise, SuppressibleMsgBox acts the same as the regular MsgBox.

TaskDialogMsgBox function TaskDialogMsgBox(const Instruction, Text: String; const Typ: TMsgBoxType; const Buttons: Cardinal; const ButtonLabels: TArrayOfString; const ShieldButton: Integer): Integer;

Displays a message box using a task dialog:
Instruction specifies the instruction to display.
Text specifies the message to display.
Typ specifies which icon to display in the task dialog. If set to mbConfirmation, no icon will be displayed.
Buttons specifies which buttons to include in the task dialog.
ButtonLabels specifies which custom button labels to use. If set to an empty array, the system's default button labels will be used. If a label consists of two strings separated by a newline, then the first string specifies the button label and the second string specifies the button note. If Buttons is set to MB_OKCANCEL, MB_YESNOCANCEL, or MB_RETRYCANCEL, specifying a label for the Cancel button as the last element in the array is optional.
ShieldButton specifies which button to display a shield icon on. If set to 0, no shield icon will be displayed.

Returns an ID* constant indicating the button the user clicked, or 0 if the function fails (which shouldn't happen unless an invalid parameter is specified or system resources are exhausted).

TMsgBoxType is defined as:

TMsgBoxType = (mbInformation, mbConfirmation, mbError, mbCriticalError);

Supported values for Buttons are:

MB_OK, MB_OKCANCEL, MB_YESNOCANCEL, MB_YESNO, MB_RETRYCANCEL, MB_ABORTRETRYIGNORE

If MB_ABORTRETRYIGNORE is used, ButtonLabels may not be an empty array and the button labels must be specified in the following special order: Retry, Ignore, Abort.

Supported values for ShieldButton and possible return values are:

IDOK, IDCANCEL, IDRETRY, IDYES, IDNO, IDABORT, IDIGNORE

begin
  case TaskDialogMsgBox('Choose A or B',
                        'You can choose A or B.',   
                        mbInformation,
                        MB_YESNOCANCEL, ['I choose &A'#13#10'A will be chosen.', 'I choose &B'#13#10'B will be chosen.'],
                        IDYES) of
    IDYES: MsgBox('You chose A.', mbInformation, MB_OK);
    IDNO: MsgBox('You chose B.', mbInformation, MB_OK);
  end;
end;

SuppressibleTaskDialogMsgBox
MsgBox

SuppressibleTaskDialogMsgBox function SuppressibleTaskDialogMsgBox(const Instruction, Text: String; const Typ: TMsgBoxType; const Buttons: Cardinal; const ButtonLabels: TArrayOfString; const ShieldButton: Integer; const Default: Integer): Integer;

Displays a suppressible message box using a task dialog. If message boxes are being suppressed (see Setup Command Line Parameters), Default is returned. Otherwise, SuppressibleTaskDialogMsgBox acts the same as the regular TaskDialogMsgBox.

GetOpenFileName function GetOpenFileName(const Prompt: String; var FileName: String; const InitialDirectory, Filter, DefaultExtension: String): Boolean;

Displays a dialog box that enables the user to select an existing file. Returns True if the user selected a file, False otherwise. The name of the selected file is returned in the FileName string.

An example Filter: 'Text files (*.txt)|*.txt|All files (*.*)|*.*'

var
  FileName: String;
begin
  // Set the initial filename
  FileName := '';
  if GetOpenFileName('', FileName, '',
     'Text Documents (*.txt)|*.txt|All Files|*.*', 'txt') then
  begin
    // Successful; user clicked OK
    // FileName contains the selected filename
  end;
end;
GetOpenFileNameMulti function GetOpenFileNameMulti(const Prompt: String; var FileNameList: TStrings; const InitialDirectory, Filter, DefaultExtension: String): Boolean;

Displays a dialog box that enables the user to select one or more existing file(s). Returns True if the user selected a file, False otherwise. The name of the selected file(s) is returned in the FileNameList list.

An example Filter: 'Text files (*.txt)|*.txt|All files (*.*)|*.*'

var
  FileNameList: TStrings;
begin
  // Create the list
  FileNameList := TStringList.Create;
  try
    if GetOpenFileNameMulti('', FileNameList, '',
       'Text Documents (*.txt)|*.txt|All Files|*.*', 'txt') then
    begin
      // Successful; user clicked OK
      // FileNameList contains the selected filename(s)
    end;
  finally
    FileNameList.Free;
  end;
end;
GetSaveFileName function GetSaveFileName(const Prompt: String; var FileName: String; const InitialDirectory, Filter, DefaultExtension: String): Boolean;

Displays a dialog box that enables the user to select a new file. Returns True if the user selected a file, False otherwise. The name of the selected file is returned in the FileName string.

An example Filter: 'Text files (*.txt)|*.txt|All files (*.*)|*.*'

var
  Filename: String;
begin
  // Set the initial filename
  Filename := '';
  if GetSaveFileName('', Filename, '',
     'Text Documents (*.txt)|*.txt|All Files|*.*', 'txt') then
  begin
    // Successful; user clicked OK
    // Filename contains the selected filename
  end;
end;
BrowseForFolder function BrowseForFolder(const Prompt: String; var Directory: String; const NewFolderButton: Boolean): Boolean;

Displays a dialog box that enables the user to select a directory. The current value of Directory is used as the initially selected directory. If NewFolderButton is True, a New Folder button will be shown, allowing the user to create new folders. Returns True if the user selected a directory and clicked OK, False otherwise. The selected directory is returned in the Directory string.

ExitSetupMsgBox function ExitSetupMsgBox: Boolean;

Displays the "Exit Setup?" message box, and returns True if the user selects Yes. Does not terminate Setup or Uninstall.

SelectDisk function SelectDisk(const DiskNumber: Integer; const AFilename: String; var Path: String): Boolean;

Displays the "Setup Needs the Next Disk" message box, and returns True if the user enters a path containing the file specified by AFileName and selects OK. The selected path is returned in the Path string. The current value of Path is used as the initially selected path and DiskNumber is used only as information to the user.

COM Automation objects support CreateOleObject function CreateOleObject(const ClassName: String): Variant;

See the Using COM Automation objects topic.

GetActiveOleObject function GetActiveOleObject(const ClassName: String): Variant;

See the Using COM Automation objects topic.

IDispatchInvoke function IDispatchInvoke(Self: IDispatch; PropertySet: Boolean; const Name: String; Par: array of Variant): Variant;

Use IDispatchInvoke to access a COM Automation property or method whose name is a reserved word.

var
  AObject: Variant;
  AType: String;
begin
  AObject := CreateOleObject('MyObject');
  // Set a property named 'Type'
  // Cannot use "AObject.Type := 'MyType';" because Type is a reserved word
  IDispatchInvoke(AObject, True, 'Type', ['MyType']);
  // Get a property or call a method named 'Type'
  AType := IDispatchInvoke(AObject, False, 'Type', ['']);
end;

Using COM Automation objects

CreateComObject function CreateComObject(const ClassID: TGUID): IUnknown;

See the Using COM Automation objects topic.

StringToGUID function StringToGUID(const S: String): TGUID;

StringToGUID converts the string representation of a GUID into a 'real' GUID. An exception will be raised upon failure.

Using COM Automation objects

OleCheck procedure OleCheck(Result: HResult);

Use OleCheck to wrap any IUnknown based COM methods you call, so that if that method fails, an exception will be raised.

OleCheck is called automatically when the method declaration specifies the safecall calling convention.

Using COM Automation objects

CoFreeUnusedLibraries procedure CoFreeUnusedLibraries;

See the Using COM Automation objects topic.

Setup Logging Log procedure Log(const S: String);

Logs the specified string in Setup's or Uninstall's log file and/or in the Compiler IDE's "Debug Output" view.

Calls to this function are ignored if logging is not enabled (via the /LOG command line parameter or the SetupLogging [Setup] section directive or the UninstallLogging [Setup] section directive or debugging from the Compiler IDE).

LogFmt

LogFmt procedure LogFmt(const S: String; const Args: array of const);

Formats the string S using the series of arguments in the open array Args, and then logs it.

function OnDownloadProgress(const Url, FileName: String; const Progress, ProgressMax: Int64): Boolean;
begin
  LogFmt('%s->%s: %d/%d', [Url, FileName, Progress, ProgressMax]);
  Result := True;
end;

Log
Format

ExecAndCaptureOutput function ExecAndCaptureOutput(const Filename, Params, WorkingDir: String; const ShowCmd: Integer; const Wait: TExecWait; var ResultCode: Integer; var Output: TExecOutput): Boolean;

Identical to Exec except:

Program output from the stdout and stderr streams is captured. This is different from ExecAndLogOutput which merges the streams.

Console programs are always hidden and the ShowCmd parameter only affects GUI programs, so always using SW_SHOWNORMAL instead of SW_HIDE is recommended.

An exception will be raised if there was an error setting up output redirection (which should be very rare).

Parameter Wait must always be set to ewWaitUntilTerminated when calling this function.

TExecOutput is defined as:

  TExecOutput = record
    StdOut: TArrayOfString;
    StdErr: TArrayOfString;
    Error: Boolean;
  end;

Error will be True if there was an error reading the output (which should be very rare) or if the output is too big. The error is logged in Setup's or Uninstall's log file and/or in the Compiler IDE's "Debug Output" view. There is no further output after an error.

Output is limited to a total size of 10 million bytes or a maximum of 1 million lines.

var
  ResultCode: Integer;
  Output: TExecOutput;
begin
  try
    // Get the system configuration
    Result := ExecAndCaptureOutput(ExpandConstant('{cmd}'), '/c systeminfo', '', SW_SHOWNORMAL, ewWaitUntilTerminated, ResultCode, Output);
  except
    Result := False;
    Log(GetExceptionMessage);
  end;

  if Result then begin
    // Do something with the Output.StdOut array of string
  end;
end;

Exec
ExecAndLogOutput
ExecAndCaptureOutputWithNativeSysDir

ExecAndLogOutput function ExecAndLogOutput(const Filename, Params, WorkingDir: String; const ShowCmd: Integer; const Wait: TExecWait; var ResultCode: Integer; const OnLog: TOnLog): Boolean;

Identical to Exec except:

Console programs are always hidden and the ShowCmd parameter only affects GUI programs, so always using SW_SHOWNORMAL instead of SW_HIDE is recommended.

If OnLog is set to nil then the output of the executed executable or batch file is logged in Setup's or Uninstall's log file and/or in the Compiler IDE's "Debug Output" view.

If OnLog is not set to nil then the output is sent to the specified function, line by line.

An exception will be raised if there was an error setting up output redirection (which should be very rare).

Parameter Wait must always be set to ewWaitUntilTerminated when calling this function.

TOnLog is defined as:

TOnLog = procedure(const S: String; const Error, FirstLine: Boolean);

Parameter S is the output line when Error is False, otherwise an error message. FirstLine is True if this is the first line of output from the program, otherwise False.

Error will be True if reading the output failed (which should be very rare), or if the output is too big. There is no further output after an error.

Output is limited to a total size of 10 million bytes or a maximum of 1 million lines.

var
  Line: String;

procedure ExecAndGetFirstLineLog(const S: String; const Error, FirstLine: Boolean);
begin
  if not Error and (Line = '') and (Trim(S) <> '') then
    Line := S; { First non-empty line found, store it }
  if FirstLine then
    Log('Output:');
  Log(S);
end;

function ExecAndGetFirstLine(const Filename, Params, WorkingDir: String; var ResultCode: Integer): String;
begin
  Line := '';
  try
    ExecAndLogOutput(Filename, Params, WorkingDir, SW_SHOWNORMAL, ewWaitUntilTerminated, ResultCode, @ExecAndGetFirstLineLog);
  except
    Log(GetExceptionMessage);
  end;
  Result := Line;
end;

Exec
ExecAndCaptureOutput
ExecAndLogOutputWithNativeSysDir

ExecAndCaptureOutputWithNativeSysDir function ExecAndCaptureOutputWithNativeSysDir(const Filename, Params, WorkingDir: String; const ShowCmd: Integer; const Wait: TExecWait; var ResultCode: Integer; var Output: TExecOutput): Boolean;

Use this function instead of ExecAndCaptureOutput to launch an executable located in the 64-bit System directory from a 32-bit installer.

This function avoids the problem that ExecAndCaptureOutput in a 32-bit installer can only launch such an executable using the Sysnative alias, while that alias is not available to 64-bit applications. To achieve this, the function temporarily disables WOW64 file system redirection.

On 32-bit Windows or in a 64-bit installer, this function is just an alias for ExecAndCaptureOutput.

ExecAndLogOutputWithNativeSysDir function ExecAndLogOutputWithNativeSysDir(const Filename, Params, WorkingDir: String; const ShowCmd: Integer; const Wait: TExecWait; var ResultCode: Integer; const OnLog: TOnLog): Boolean;

Use this function instead of ExecAndLogOutput to launch an executable located in the 64-bit System directory from a 32-bit installer.

This function avoids the problem that ExecAndLogOutput in a 32-bit installer can only launch such an executable using the Sysnative alias, while that alias is not available to 64-bit applications. To achieve this, the function temporarily disables WOW64 file system redirection.

On 32-bit Windows or in a 64-bit installer, this function is just an alias for ExecAndLogOutput.

Other Sleep procedure Sleep(const Milliseconds: Cardinal);

Suspends the execution of Setup or Uninstall for a specified interval.

Random function Random(const Range: Integer): Integer;

Returns a random number within the range 0 <= X < Range.

Beep procedure Beep;

Beeps.

Beep; //Beeps
Round function Round(const E: Extended): Int64;

Returns the value of E rounded to the integer number.

If E is exactly halfway between two integer numbers, the result is always the even number. This method of rounding is often called "Banker's rounding."

Trunc function Trunc(const E: Extended): Int64;

Returns the truncated value of E; that is, E rounded toward zero, as an integer number.

Int function Int(const E: Extended): Extended;

Returns the integer part of E; that is, E rounded toward zero.

MulDiv function MulDiv(const Number, Numerator, Denominator: Integer): Integer;

Multiplies two 32-bit values (Number and Numerator) and then divides the 64-bit result by a third 32-bit value (Denominator). The final result is rounded to the nearest integer.

If the result is a positive half integer (ends in .5), it is rounded up. If the result is a negative half integer, it is rounded down.

Set8087CW procedure Set8087CW(NewCW: Word);

Sets the FPU control word.

Set8087CW($133f); //Disables all fpu exceptions }
Get8087CW function Get8087CW: Word;

Returns the current value of the FPU control word.

BringToFrontAndRestore procedure BringToFrontAndRestore;

Makes sure that Setup or Uninstall is visible and the foreground window.

Deprecated LoadDLL function LoadDLL(const DLLName: String; var ErrorCode: Integer): HMODULE;

Loads the specified DLL. Returns the DLL handle if the DLL was loaded successfully, zero otherwise. If zero is returned then ErrorCode specifies the error that occurred. Use SysErrorMessage(ErrorCode) to get a description of the error.

This function is deprecated. See the Using DLLs topic.

Refer to the system error codes on MSDN.

CallDLLProc function CallDLLProc(const DLLHandle: HMODULE; const ProcName: String; const Param1, Param2: NativeInt; var Result: NativeInt): Boolean;

Calls the specified function in a DLL specified using the DLL handle returned by LoadDLL. Returns True is the procedure was called successfully, False otherwise.
The function must use the standard calling convention, accept two 4 byte integer parameters and return a 4 byte integer result.

This function is deprecated. See the Using DLLs topic.

FreeDLL function FreeDLL(const DLLHandle: HMODULE): Boolean;

Unloads a DLL specified using the DLL handle returned by LoadDLL.

This function is deprecated. See the Using DLLs topic.

CastStringToInteger function CastStringToInteger(var S: String): LongInt;

Casts a string to an integer so that a string can be passed to a DLL using CallDllProc.

This function is deprecated. See the Using DLLs topic.

CastIntegerToString function CastIntegerToString(const L: LongInt): String;

Casts an integer to a string so that a string can be received from a DLL using CallDllProc.

This function is deprecated. See the Using DLLs topic.

Exec and ShellExec - ShowCmd values SW_SHOW, SW_SHOWNORMAL, SW_SHOWMAXIMIZED, SW_SHOWMINIMIZED, SW_SHOWMINNOACTIVE, SW_HIDE MsgBox - Buttons flags MB_OK, MB_OKCANCEL, MB_ABORTRETRYIGNORE, MB_YESNOCANCEL, MB_YESNO, MB_RETRYCANCEL, MB_DEFBUTTON1, MB_DEFBUTTON2, MB_DEFBUTTON3, MB_SETFOREGROUND MsgBox - return values IDOK, IDCANCEL, IDABORT, IDRETRY, IDIGNORE, IDYES, IDNO Reg* - RootKey values (also see the [Registry] section documentation) HKEY_AUTO, HKEY_AUTO_32, HKEY_AUTO_64,
HKEY_CLASSES_ROOT, HKEY_CLASSES_ROOT_32, HKEY_CLASSES_ROOT_64,
HKEY_CURRENT_USER, HKEY_CURRENT_USER_32, HKEY_CURRENT_USER_64,
HKEY_LOCAL_MACHINE, HKEY_LOCAL_MACHINE_32, HKEY_LOCAL_MACHINE_64,
HKEY_USERS, HKEY_USERS_32, HKEY_USERS_64,
HKEY_PERFORMANCE_DATA,
HKEY_CURRENT_CONFIG, HKEY_CURRENT_CONFIG_32, HKEY_CURRENT_CONFIG_64,
HKEY_DYN_DATA,
HKA, HKA32, HKA64, HKCR, HKCR32, HKCR64, HKCU, HKCU32, HKCU64, HKLM, HKLM32, HKLM64, HKU, HKU32, HKU64, HKCC, HKCC32, HKCC64