Returns all command line parameters passed to Setup or Uninstall as a single string, including undocumented internal parameters used by Setup and Uninstall.
ParamStr
Returns the number of command line parameters passed to Setup or Uninstall, excluding undocumented internal parameters used by Setup and Uninstall.
ParamStr
GetCmdTail
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
Returns the name of the active language.
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;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;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;
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.
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.
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.
Returns the name or description of the setup type selected by the user.
Returns a comma-separated list of names or descriptions of the components selected by the user.
WizardIsComponentSelected
WizardSelectComponents
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;Returns a comma-separated list of names or descriptions of the tasks selected by the user.
WizardIsTaskSelected
WizardSelectTasks
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;Returns True if Setup is running silently, False otherwise.
Returns True if Uninstall is running as opposed to Setup, False otherwise.
Returns True if Uninstall is running silently, False otherwise.
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.
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.
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.
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.
Gets a value that was previously stored using SetPreviousData.
Sets a value that can be restored later using GetPreviousData. Call SetPreviousData inside a RegisterPreviousData event function, once per setting.
Returns True if Setup or Uninstall is terminating, False otherwise.
Returns True if Setup or Uninstall is being debugged by the Compiler IDE or another application, False otherwise.
Run-time debugger
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.
Returns True if a Restart Manager session was started, False otherwise.
CloseApplications
Returns the WizardForm support object, or raises an internal error if the object has not yet been created.
WizardForm
Returns the UninstallProgressForm support object, or raises an internal error if the object has not yet been created.
UninstallProgressForm
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;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;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.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
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;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;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;Returns True if Setup/Uninstall is running with administrative privileges.
Returns True if Setup is running in administrative install mode or if Uninstall is running with administrative privileges.
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
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
Returns True if the user's system is set to a high-contrast theme.
IsDarkInstallMode
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
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;Returns the version number of Windows in string form. On Windows 2000, for example, this function will return "5.00.2195".
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
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
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
Returns True if the system matches architecture identifier arm32compatible.
Architecture Identifier Matchers like IsX64Compatible
ProcessorArchitecture
Returns True if the system matches architecture identifier arm64.
Architecture Identifier Matchers like IsX64Compatible
ProcessorArchitecture
Returns True if the system matches architecture identifier x64compatible.
Architecture Identifier Matchers like IsX64Compatible
ProcessorArchitecture
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
Returns True if the system matches architecture identifier x86compatible.
Architecture Identifier Matchers like IsX64Compatible
ProcessorArchitecture
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
Returns True if Setup is built as a 64-bit x64 application, as specified by SetupArchitecture.
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
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;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;Gets the value of the specified environment variable.
Retrieves the name of the user currently logged onto the system.
Retrieves the name of the computer the Setup or Uninstall program is running on (as returned by the Windows GetComputerName function).
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;Returns True if a font with the specified face name is installed on the system.
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.
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.
Sends the specified message to the specified window. Does not return until the window procedure has processed the message.
Posts the specified message to the specified window, returning immediately. Returns True if successful.
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.
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.
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.
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.
Creates a mutex with the specified name.
Returns True if any of the mutexes in the comma-separated Mutexes string exist.
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;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;
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;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);Returns the character with the specified ordinal value.
Returns the ordinal value of the specified character, integer or enumeration value.
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.
Returns the length of the specified 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.
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.
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).
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).
Returns a string of length I with all characters set to character C.
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.
Merges Source into Dest at the position Dest[Index].
This function is deprecated. It is equivalent to calling StringChangeEx with the SupportMBCS parameter set to False.
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;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
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
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.
Opposite of AddQuotes; removes any quotes around the string.
Expands all %-encoded characters in the string (see RFC 2396). Returns True if all were successfully expanded.
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.
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.
Compares the strings S1 and S2 and returns True if they are equal. The SameText function is not case-sensitive.
Compares S1 to S2, with case-sensitivity. The return value is True if they are equal.
Returns True if the specified pattern contains a wildcard.
Returns True if the specified text matches the specified pattern.
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;Trims leading and trailing spaces and control characters from the given string S.
Trims leading spaces and control characters from the given string S.
Trims trailing spaces and control characters from the given string S.
Joins two or more strings together separated by the given separator.
var
S: String;
begin
S := StringJoin(',', ['1', '2']);
// S = '1,2'
end;
StringSplit
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
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
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.
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.
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.
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.
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.
The StrToColor function converts the string passed in S, formatted as '#rrggbb', into a color. Raises an exception if not successful.
The IntToStr function converts a 64-bit number into a string.
The FloatToStr function converts a floating point number into a string. The character used for the decimal point will always be a dot.
Returns the length in characters of the character in the specified string at the specified index, which is currently always 1.
Returns the specified string with a trailing backslash added, unless the string is empty or already ends in a slash or backslash.
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.
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.
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.
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.
Returns True if the specified path begins with a drive letter and colon, or a slash.
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.
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.
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
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
Returns the specified string with a trailing period added, unless the string is empty or already ends in a period or other punctuation mark.
Takes the file name passed in FileName and changes the extension of the file name to the extension passed in Extension.
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.
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
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
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.
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.
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;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.
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.
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
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
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', '-', ':');
Sets the length of a string.
Translates an ANSI string to a string with characters from the OEM-defined character set.
Translates a string with characters from the OEM-defined character set into an ANSI string.
Encodes a Unicode string into a UTF-8 encoded ANSI string.
Decodes a UTF-8 encoded ANSI string into a Unicode string.
Gets the MD5 sum of the specified string, as a string.
var
MD5: String;
begin
MD5 := GetMD5OfString('Test');
// MD5 = '0cbc6611f5540bd0809a388dc95a615b'
end;
Gets the MD5 sum of the specified string, as a string.
var
MD5: String;
begin
MD5 := GetMD5OfUnicodeString('Test');
// MD5 = '8e06915d5f5d4f8754f51892d884c477'
end;
Gets the SHA-1 hash of the specified string, as a string.
var
SHA1: String;
begin
SHA1 := GetSHA1OfString('Test');
// SHA1 = '640ab2bae07bedc4c163f679a746f7ab7fb5d1fa'
end;
Gets the SHA-1 hash of the specified string, as a string.
var
SHA1: String;
begin
SHA1 := GetSHA1OfUnicodeString('Test');
// SHA1 = '9ab696a37604d665dc97134dbee44cfe70451b1a'
end;
Gets the SHA-256 hash of the specified string, as a string.
var
SHA256: String;
begin
SHA256 := GetSHA256OfString('Test');
// SHA256 = '532eaabd9574880dbf76b9b8cc00832c20a6ec113d682299550d7a6e0f345e25'
end;
Gets the SHA-256 hash of the specified string, as a string.
var
SHA256: String;
begin
SHA256 := GetSHA256OfUnicodeString('Test');
// SHA256 = 'e6fa3ca87b1b641ab646d3b4933bba8d0970763f030b6578a60abdeae7366247'
end;
Returns a localized error message string that corresponds to the given operating system error code.
Refer to the system error codes on MSDN.
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
Gets the length of an array.
Sets the length of an array. Always call SetArrayLength before accessing the elements in an array.
Gets the SHA-256 hash of the specified stream, as a string. An exception will be raised upon failure.
GetSHA256OfFile
Returns a variant with a value of Null.
Returns a variant with no value assigned.
Returns True if the specified variant is unassigned.
VarIsClear
Returns True if the specified variant's value is undefined.
VarIsEmpty
Returns True if the specified variant has a value of Null assigned.
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;
Returns the specified element of the specified variant array.
Sets the specified element of the specified variant array.
Returns True if the specified directory name exists. The specified name may include a trailing backslash.
Returns True if the specified file exists.
Returns True if the specified directory or file name exists. The specified name may include a trailing backslash.
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.
Sets Size to the size of the specified file in bytes. Returns True if the file size was set successfully and False otherwise.
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
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
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.
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
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
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
Returns a string containing the name of the current directory.
Sets the current directory. The return value is True if the current directory was successfully changed, or False if an error occurred.
Returns fully qualified path of the Windows directory. Only includes a trailing backslash if the Windows directory is the root directory.
Returns fully qualified path of the Windows System directory. Only includes a trailing backslash if the Windows System directory is the root directory.
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;Returns fully qualified path of the temporary directory, with trailing backslash. Uses the Win32 function GetTempPath2 if available, and GetTempPath otherwise.
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;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.
Generates a unique filename for a file in the specified path with the specified extension.
Returns True if the specified file is protected by Windows File Protection (and therefore can't be replaced).
Calls ApplyPathRedirRules function with the current process as the target process.
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:
| A64Bit | APath | ATargetProcess64Bit | Result | Explanation |
| True | System32 | False | Sysnative | The 32-bit target process needs to use the Sysnative alias to access 64-bit system files. |
| False | System32 | True | SysWOW64 | The 64-bit target process needs to use SysWOW64 to access 32-bit system files. |
| False | System32 | False | SysWOW64 | Helps the 32-bit target process avoid some exceptions that apply to System32 but not to SysWOW64. |
| Any value | Sysnative | True | System32 | The 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
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.
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
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.
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
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.
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;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;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;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
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;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
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.
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.
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
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;Gets the MD5 sum of the specified file, as a string. An exception will be raised upon failure.
Gets the SHA-1 hash of the specified file, as a string. An exception will be raised upon failure.
Gets the SHA-256 hash of the specified file, as a string. An exception will be raised upon failure.
GetSHA256OfStream
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
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.
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.
Erases the file named by FileName from the disk.
If the file cannot be deleted or does not exist, the function returns False.
Attempts to delete Filename, retrying up to Tries times if the file is in use. It delays 250 msec between tries.
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.
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
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
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
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
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);
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
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
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
Creates a new directory. The return value is True if a new directory was successfully created, or False if an error occurred.
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.
Deletes an existing empty directory. The return value is True if the empty directory was successfully deleted, or False if an error occurred.
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;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);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.
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.
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.
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.
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.
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.
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.
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.
Unregisters the font with the specified face and filename.
Changes the "Close on exit" setting of a .pif file. Returns True if it was able to make the change.
Gets the version numbers of the specified file. Returns True if successful, False otherwise.
PackVersionNumbers
Gets the individual version components of the specified file. Returns True if successful, False otherwise.
PackVersionComponents
Gets the version of the specified file as a string (in "0.0.0.0" format). Returns True if successful, False otherwise.
Gets the packed version of the specified file. Returns True if successful, False otherwise.
Always use ComparePackedVersion or SamePackedVersion to compare packed versions.
PackVersionComponents
Packs version numbers into a single value.
Always use ComparePackedVersion or SamePackedVersion to compare packed versions.
GetVersionNumbers
PackVersionComponents
UnpackVersionNumbers
Packs individual version components into a single value.
Always use ComparePackedVersion or SamePackedVersion to compare packed versions.
GetVersionComponents
PackVersionNumbers
UnpackVersionComponents
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.
Compares the packed versions Version1 and Version2 and returns True if they are equal.
Unpacks a packed version into version numbers.
UnpackVersionComponents
PackVersionNumbers
Unpacks a packed version into individual version components.
UnpackVersionNumbers
PackVersionComponents
Returns the specified packed version as a string (in "0.0.0.0" format).
StrToVersion
UnpackVersionNumbers
UnpackVersionComponents
Returns the specified string (in "0.0.0.0" format) as a packed version. Returns True if successful, False otherwise.
VersionToStr
PackVersionNumbers
PackVersionComponents
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;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;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;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;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;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).
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;Queries the specified registry value, and returns the data in ResultStr. Returns True if successful. When False is returned, ResultStr is unmodified.
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;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;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;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;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;Deletes the specified key and all subkeys. Returns True if successful, False otherwise.
Deletes the specified subkey if it has no subkeys or values. Returns True if successful, False otherwise.
Deletes the specified value. Returns True if successful, False otherwise.
Returns True if the specified INI key exists.
Returns True if the specified INI section is empty.
Reads a Boolean from an INI file.
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.
Reads a String from an INI file.
Writes a Boolean to an INI file.
Writes a LongInt to an INI file.
Writes a string to an INI file.
Deletes the specified section from an INI file.
Deletes the specified key from an INI file.
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
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
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
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
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
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
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
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
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
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
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
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
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
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;
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.
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.
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.
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
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.
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
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
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.
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
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.
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;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;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;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.
Displays the "Exit Setup?" message box, and returns True if the user selects Yes. Does not terminate Setup or Uninstall.
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.
See the Using COM Automation objects topic.
See the Using COM Automation objects topic.
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
See the Using COM Automation objects topic.
StringToGUID converts the string representation of a GUID into a 'real' GUID. An exception will be raised upon failure.
Using COM Automation objects
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
See the Using COM Automation objects topic.
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
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
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
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
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.
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.
Suspends the execution of Setup or Uninstall for a specified interval.
Returns a random number within the range 0 <= X < Range.
Beeps.
Beep; //Beeps
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."
Returns the truncated value of E; that is, E rounded toward zero, as an integer number.
Returns the integer part of E; that is, E rounded toward zero.
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.
Sets the FPU control word.
Set8087CW($133f); //Disables all fpu exceptions }
Returns the current value of the FPU control word.
Makes sure that Setup or Uninstall is visible and the foreground window.
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.
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.
Unloads a DLL specified using the DLL handle returned by LoadDLL.
This function is deprecated. See the Using DLLs topic.
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.
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.