NSIS 简易教程(三)

;目前可用的callback functions:
1、 .onGUIInit
;this callback will be called just before the first page is loaded and the installer dialog is shown
; allowing you to tweak(调整) the user interface

!include “WinMessages.nsh”
Function .onGUIInit
GetDlgItem $R0 $HWNDPARENT 1028
CreateFont $R1 “Tahoma” 10 700
SendMessage $R0 ${WM_SETFONT} $R1 0
#set background color to white and text color to red
SetCtlColors $R0 FFFFFF FF0000

2、 .onInit;即将完成初始化
;this function will be called when the installer is nearly finished initializing. if the ‘.onInit’ function
; calls abort,the installer will quit instantly.

Function .onInit
MessageBox MB_YESNO “This will install .Continue?” IDYES NoAbort
Abort;causes installer to quit.

3、 .onInstFailed;安装失败时点击取消
;this callback is called when the user hits the ‘cancel’ button after the install has failed

Function .onInstFailed
MessageBox MB_OK “Better luck next time.”

4、 .onInstSuccess ;安装成功窗口关闭前
;this callback is called when the install was successful,right before the install window closes(which
;may be after the user clicks ‘Close’ if AutoCloseWindow or SetAutoClose is set to false)

Function .onInstSuccess
MessageBox MB_YESNO “Congrats,it worked.View readme?” IDNO NoReadme
Exec notepad.exe;view readme or whatever if you want.

5、 .onGUIEnd;;安装成功窗口关闭后
;this callback is called right after the installer window closes.Use it to free any user interface
;related plug-ins if needed

6、 .onMouseOverSection;鼠标放置的session发生变化是被调用,可以用于改变描述信息
;this callback is called whenever the mouse position over the sections tree has changed.this allows
;you to set a description for each section for example.this section id on which the mouse is over
;currently is stored ,temporarily,in $0

Function .onMouseOverSection
FindWindow $R0 “#32770” “” $HWNDPARENT
GetDlgItem $R0 $R0 1043
StrCmp $0 0 “” +2
SendMessage $R0 ${WM_SETTEXT} 0 “STR:first section description”
StrCmp $0 1 “” +2
SendMessage $R0 ${WM_SETTEXT} 0 “STR:second section description”

7、 onRebootFailed;自动重启失败
;this callback is called if Reboot fails.WritUninstaller,plug-ins,File and WriteRegBin should not be used
;in this callback

Function .onRebootFailed
MessageBox MB_OK|MB_ICONSTOP “Reboot failed,Please reboot manually.” /SD IDOK

8、 onSelChange;选择发生变化
;called when the selection changes on the component page.Usefull for using with SectionSetFlags and
;SectionSetFlags and SectionGetFlags.
;selection changes include both section selection and installation type change.

9、 onUserAbort
;called when the user hits the ‘cancel’ button,and the install hasn’t already failed.If this function
;calls Abort,the install will not be aborted.

MessageBox MB_YESNO “Abort install?” IDYES NoCancelAbort
do something

10、 .onVerifyInstDir
;enables control over whether or not an installation path is valid for your installer. This code will be
;called every time the user changes the install directory,so it shouldn’t do anything crazy with MessageBox
;or the likes.If this function calls Abort,the installation path in $INSTDIR is deemed invalid.

IfFileExists $INSTDIR\Winamp.exe PathGood
Uninstall Callbacks

11、 un.onGUIInit;卸载程序的类似于.onGUIInit
;called just before the first page is loaded and the installer dialog is shown, allowing you to tweak the
;user interface.

12、 un.onInit;若调用了Abort,程序直接退出,在有必要时检查一下$INSTDIR
;this callback will be called when the uninstaller is nearly finished initializeing.If the
;’un.onInit’ function calls Abort,the uninstaller will quit instantly.Note that this function can verify
;and/or modify $INSTDIR if necessary.

Function un.onInit
MessageBox MB_YESNO “This will uninstall.” IDYES NoAbort
Function un.onInit
IfFileExists $INSTDIR\myfile.exe found
MessageBox MB_OK “Uninstall path incorrent”

13、 un.onUninstFailed
;called when the user hits the ‘cancel’ button after the uninstall has failed(if it used the
;Abort command or otherwise failed).

14. un.onUninstSuccess
15. un.onGUIEnd
16. un.onRebootFailed
17. un.onSelChange
18. un.onUserAbort
Installer Attributes
these attributes control how the installer looks and functions,including which pages are present in the
installer ,as what text is displayed in each part of each page,how the installer is named,what icon the
installer uses,the default installation directory,what file it writes out,and more,note that these attributes
can be set anywhere in the file except in a Section or Function .

1、 AddBrandingImage
为installer添加一个图标,但不是icon,its size will be set according to the width/height specified,the installer’s
width/height and the installer font,the final size will not always be what you requested;
AddBrandingImage only adds a placeholder for an image,to set the image itself on runtime,use SetBrandingImage

2、 AllowRootDirInstall
controls whether or not installs are enabled to the root directory of a dirve,or directly into a network
share,set to true to change the safe behavior,which prevents users from selecting C:\ or \\Server\Share as an
install(and later on ,uninstall)directory,for additional directory selection page customizability,

3、 AutoCloseWindow[true]/[false]
Set whether or not the install window automatically closes when completed.This is overrideable from a
section using SetAutoClose

4、 BGFont;设置背景gradient上的字体
Specifies the font used to show the text on the background gradient.To set the color use BGGradient.
IF no parameters are specified ,the default font will be used,the default font is bold and italic Times New Roman

5、 BGGradient;设置背景gradient上字体的颜色,以及是否显示这样一个渐变背景

6、 BrandingText /TRIM(LEFT|RIGHT|CENTER) text
添加一些文字,但不是窗口标题,缺省的是”Nullsoft Install System Vx.xx”,text is shown at the bottom of the
install winidow,setting this to an empty string(“”) uses the default; to set the string to blank use ” ”
accepts variables .if variables are used,they must be initialized on .onInit

7、 Caption caption
when used outside a PageEx block:set the text for the titlebar of the installer,the By default,it is
‘Name Setup’,where name is specified with the Name instruction.You can howerver,override it with
‘My App installer’ or whatever
when used in a PageEx block:sets the subcaption of the current page.
accepts variables .if variables are used,they must be initialized on .onInit

8、 ChangeUI dialog ui_file.exe
by a dialog with the same resource ID in ui_file.exe.you can also specify ‘all’ as the dialog if you
wish to replace all 7 of the dialogs at one from the same UI file:
a.IDD_LICENSE must contain IDC_EDIT1(RICHEDIT control)
b.IDD_DIR must contain IDC_DIR(edit box),IDC_BROWSE(button) and IDC_CHECK1(checkbox)
c.IDD_SELCOM must contain IDC_TREE1(SysTreeView32 control),and IDC_COMBO1(combo box)
d.IDD_INST must contain IDC_BACK(button).If an image control (static with SS_BITMAP style) will be found
in this dialog it will be used as the default fro SetBrandingImage.
e.IDD_INSTFILES must contain IDC_LIST1(SysListView32 control),IDC_PROGRESS(msctls_progress32 control),and
f.IDD_UNINST must contain IDC_EDIT1(edit box)
g.IDD_VERIFY must contain IDC_STR(static).
ChangeUI all “${NSISDIR}\Contrib\UIs\sdbarker_tiny.exe”

9、 CheckBitmap bitmap.bmp ;规格:96*16 pixels 状态selection mask,checked,greyed out, unchecked&read-only…
Specifies the bitmap with the images used for the checks of the component-selection page treeview.

10、 CompletedText text
Replaces the default text(“Completed”) that is Printed at the end of the install if parmeter is specified
Otherwise the default is used.
accepts variables,but they should be initialized before the message is printed!

11、 ComponentText [text [subtext] [subtext2]]
Used to change the default text on the component page.
text:Text above the controls,to the right of the installation icon.
Subtext:Text next to the installation type selection
subtext2:Text to the left of the components list and below the installation type
the default string will be used if a string is empty(“”)
accepts variables…..

12、 DetailsButtonText show details text
replace the default details button text

13、 DirText [text] [subtext] [browse_button_text] [browse_dlg_text]
used to change the default text on the directory page.
text: text above the controls to the right of the installation icon.
subtext: text on the directory selection frame.
browse_button_text:text on the browse button
browse_dlg_text:text on the “browse for folder” dialog,appears after clicking on “Browse” button
defalut “”

14、 DirVar user_var(dir input/output)
specifies which variable is to be used to contain the directory selected.this variable should contain
the default value too. this allows to easily create two different directory pages that not require you
to move values in and out of $INSTDIR,the default variable is $INSTDIR,This can only be used in PageEx and
for directory and uninstConfirm pages.

15、 DirVerify auto|leave
if DirVerify leave is used,the Next Button will not be disabled if the dir is not valid

16、 FileErrorText file error text
Replaces the default text that comes up when a file cannot be written to.

17、 Icon [patn\]icon.ico
use UninstallIcon to set the Uninstaller icon.

18、 InstallButtonText install button text
;overrides the default install button text(of “Install”) with the specified text
;accept variables.

19、 InstallColors /windows|(foreground_color background_color)
;set the colors to use for the install info screen
;/windows 指示使用默认的前景和背景色

20、 InstallDir definstdir
Sets the default installation directory.
21、 InstallDirRegKey root_key subkey key_name
;this attribute tells the installer to check a string in the registry,and use it for the install dir if
;that string is valid.
;Language strings和变量不能被使用
InstallDirRegKey HKLM Software\NSIS “ABC.EXE”

22、 InstProgressFlags [flag[….]]
;flag的有效值是:smooth or colored

InstProgressFlags smooth
InstProgressFlags smooth colored
when XPStyle on …

;add an install type to the install type list,or disables the custom install type.
;there can be as many as 32 types,each one specifying the name of the install type.
;如果前面有’.un’前缀,则是卸载类型,名字中可以包含变量,which will be processed at runtime before the
components page shows.another way of changing the InstType name during runtime is the InstTypeSetText
command.the difference is that with InstTypeSetText you are saving your precious user variables,the first
type is the default (generally ‘Typical’).If the /NOCUSTOM switch is specified,then the “custom” install
type is disabled,and the user has to choose one of the pre-defined install types,Alternatively,if the
/CUSTOMSTRING switch is specified,the parameter will override the “custom” install type text,Alternatively
if the /COMPONENTSONLYONCUSTOM flag is specified th ecomponent list will only be shown if the “Custom”
install type is selected.

24、 LicenseBkColor color | /gray | /windows
;Sets the background color of the license data.Color is specified using the form RPGGBB

25、 LicenseData licdata.(txt|rtf)
;LicenseData lic.txt
;LicenseData lic.rtf
use LicenseLangString to show a different license for every language

26、 LicenseForceSelection (checkbox [accept_text] |radiobuttons [accept_text] [decline_text]|off)
;Specifieds if the displayed license must be accept explicit or not.
;if off is specified the “next button ” is enabled by default.

27、 LicenseText [text [button_text]]
; Used to change the default text on the license page.
;text: Text above the controls,to the right of the installation icon.
;button_text:text on the “I Agree” button.
;default string will be used if a string is empty(“”).

28、 MiscButtonText[back button text [next button text]] [cancel button text] [close button text]
;Replaces the default text strings for the four buttons(Back,Next,Cancel,Close)
;accept variables.

29、 Name name[name_coubled_ampersands]
;Name “MyAPP” = “MyAPP”
;Name “Foo & Bar” “Foo && Bar” = “Foo & bar”

30、 OutFile [path\]install.exe
;Specifies the output file that the MakeNSIS should write the installer to .
;this is just the file that MakeNSIS writes,it doesn’t affect the contents of the installer.

31、 RequestExecutionLevel none|user|highest|admin
;Specifies the requested execution level for windows Vista and wiindows 7

32、 SetFont [/LANG = lang_id] font_face_name font_size
;Set the installer font.
;SetFont /LANG=${LANG_ENGLISH} “english font” 9

33、 ShowInstDetails hide|show|nevershow
;Sets whether or not the details of the uninstall are shown.default is hide
note that sectins can override this using SetDetailsView

34、 ShowUninstDetails hide|show|nevershow
;Sets whether or not the details of the uninstall are shown. default is hide.
note that sectins can override this using SetDetailsView

35、 SilentInstall normal|silent|silentlog
Specifies whether or not the installer should be silent.If it is ‘silent’ or ‘silentlog’,all sections
that have the SF_SELECTED flag are installed quietly(you can set tis flag using SectionSetFlags),with
no screen output from the installer ifself

36、 SilentUnInstall normal |silent

37、 SpaceTexts [reg text [avail text]]
if parameters are specified,overrides the space required and space available text(“Space required:” and
“Space available:” by default). IF ‘none’ is specified as the required text no space texts will be shown.

38、 SubCaption [page_number subcaption]
Overrides the subcaptions for each of the installer pages (0=”:License Agreement”,1=”:Installation Options”…)
you can also set a subcaption using Caption inside a PageEx block

39 UninstallButtonText text
Changes the text of the button that by default says “Unistall” in the uninstaller

40 UninstallCaption caption
sets what the titlebars of the uninstaller will display, default it is ‘Name Uninstall’
UninstallCaption “myapp Uninstall”

41 UninstallIcon [path\]icon.ico
sets the icon of the uninstaller

42 UninstallSubCaption page_number subcaption
set the default subcaptions for the uninstaller pages(0=”:Confirmation”,1=”:Uninstalling Files”,
using Caption inside a PageEx block

43 UninstallText text [subtext]
Specifies the texts on the uninstaller confirm page.

44 WindowIcon on|off
Sets whether or not the installer’s icon is being displayed

45 XPStyle on|off
Set whether or not an XP manifest will be added to the installer,
this affects the uninstaller too.
Compiler Flags
the following commands affect how the compiler generates code and compresses data.Unless otherwise noted,
these commands are valid anywhere in the script,and effect every line below where each one is placed until
overridden by another command,they cannot be jumped over using flow control instruction
46 AllowSkipFiles on|off
;on 时允许user skip file,off时,只有abort安装
this command specifies whether the user should be able to skip a file or not.
a user has an option to skip a file if SetOverwrite is set to on,and the installer fails to open a file
for writing when trying to extract a file. if off is used the ignore button which allows the user to skip
the file will not show and the user will only have an option to abort the installation

47 FileBufSize buffer_size_in_mb
this command sets the size of the compiler’s internal file buffers. This command allows you to control the
compiler’s memory usage by limiting how much of a given file it will load into memory at once.since the
compiler needs both input and output,twice the memory size specified could be used at given time for file

48 SetCompress auto|force|off
this command sets the compress flag which is used by the installer to determine whether or not data should
be compressed

49 SetCompressor [/SOLID][/FINAL] zlib|bzip2|lzma
this command sets the compression algorithm used to compress filese/data in the installer.
ZLIB: (the default) it is a quick and simple method, 300kb memory uses
BZIP2: gives better compression raios than ZLIB but a bit slower and uses more memory,4M memory uses
LZMA: a new compression method that gives very good compression ratios,compression speed is lower but
decompression speed is high ,8M memory uses
if /FINAL is used,subsequent calls to SetCompressor will be ignored.即后面的调用将被忽略
if /SOLID is used,all of the installer data is compressed in one block,result in greater compression ratios

50 SetCompressorDictSize dict_size_mb
Sets the dictionary size in megabytes used by the LZMA compressor

51 SetDatablockOptimize on|off
this command tells the compiler whether or not to do datablock optimizations.Datablock optimizations have
the compiler check

52 SetDateSave on|off
this command sets the file date/time saving flag which is used by the File command to determine whether or
not to save the last write date and time of the file,so that it can be restored on installation.Valid flags
are ‘on’ and ‘off’ ,’on’ is default

53 SetOverwrite on|off|try|ifnewer|ifdiff|lastused
on 直接覆盖(default)
off 不覆盖
try 如果能覆盖则覆盖
ifnewer 如果存在的文件更旧
ifdiff 不同,更新或更旧
Version Information

54 VIAddVersionKey [/LANG=lang_id] keyname_value
add a field in the Version Tab of the File Properties,this can either be a field provided b the system
or a user defined field.The following fields are provided by the System:

VIAddVersionKey /LANG=${LANG_ENGLISH} “ProductName” “Test Application”
VIAddVersionKey /LANG=${LANG_ENGLISH} “Comments” “A test comment”
VIAddVersionKey /LANG=${LANG_ENGLISH} “CompanyName” “Fake company”
VIAddVersionKey /LANG=${LANG_ENGLISH} “LegalTrademarks” “Test Application is a trademark of Fake company”
VIAddVersionKey /LANG=${LANG_ENGLISH} “LegalCopyright” ” Fake company”
VIAddVersionKey /LANG=${LANG_ENGLISH} “FileDescription” “Test Application”
VIAddVersionKey /LANG=${LANG_ENGLISH} “FileVersion” “1.2.3”

55 VIProductVersion [version-string_X.X.X.X]
adds the Product Version on top of the Version Tab in the Properties of the file.
VIProductVersion “”
Basic Instructions

1. Delete [/REBOOTOK] file
/REBOOTOK 选项指定重启后删除
找到文件但无法删除 error flag is set
没有找到文件error flag is not set
Delete $INSTDIR|test.dat

2. Exec command
执行指定的program,指定的程序必须存在 $OUTDIR is used for the working directory
指定程序无法启动时,error flag is set

Exec ‘”$INSTDIR\text.exe”‘
Exec ‘”$INSTDIR\text.exe” some parameters’

使用ShellExecute来执行一个程序,通常执行”open”,”print” 等
$OUTDIR 是工作目录
error flag is set 如果无法启动

ExecShell “open” “http://nsis.sf.net”
ExecShell “open” “$INSTDIR\readme.txt”

4. ExecWait command[user_var(exit code)]
if no ouput variable is specified
如果该程序没有返回值返回nonzero error code或执行出错,error flag is set,
if an ouput variable is specified
该函数将用exit code 填充变量,

ExecWait ‘”$INSTDIR\test.exe”‘
ExecWait ‘”$INSTDIR\text.exe”‘ $0
ExecWait ‘”$INSTDIR\text.exe” some parameters’

5. File
.output file name is $OUTDIR\filename_portion_of_file
.use /oname = x switch to 改变output name.x可以包含变量,可以是相对或绝对路径,若包含space 请加上””
.if /r is used, 递归查找子文件夹
. /x is used to exclude files or directories.排除不需要的文件或文件夹
. /a is used,the attributes of the files added will be preserved.
. if /nonfatal is used and no files are found,a warning will be issued instead of an error

File something.exe
File /a someting.exe
File *.exe
File /r *.dat
File /r data
File /oname=temp.dat somefile.ext
File /oname=$TEMP\temp.dat somefile.ext
File “/oname=$TEMP\name with spaces.dat” somefile.ext
File /nonfatal “a file that might not exist”
File /r /x CVS myProject\*.*
File /r /x *.res /x *.obj /x *.pch source\*.*

注意 /r
when using the /r switch,both mathing directories and files will be searched.this is always done with or without the use
of wildcards,even if the given path perfectly matches one directory,

6. Rename [/REBOOTOK] source_file dest_file
Rename source_file to des_file
if the current folder is not set using SetOutPath instruction the current folder is $EXEDIR

Rename $INSTDIR\file.ext $INSTDIR\file.dat

7. ReserveFile [/nonfatal] [/r] [/x file|wildcard […]] file [file….]
Reserves a file in the data block for later use,
文件是按他们在脚本中出现的顺序添加到data block中,而函数则不是按他们出现的顺序被调用的
如果你在一个函数中添加一个文件,他会被早早的调用而你却把它定义在脚本的很后面,执行脚本时,all of the files added earlier will
have to be decompressed to get to the required file,

8. RMDir [/r] [/REBOOTOK] directory_name
没有 /r时,只有文件夹为空时才会被移除,
有/r 时,文件夹被递归移除
有error flag
注意:当前文件夹不能被移除, the current working directory is set by SetOutPath

SetOutPath $TEMP\dir
RMDir $TEMP\dir

The next example will succeed in deleting the directory.

SetOutPath $TEMP\dir
SetOutPath $TEMP
RMDir $TEMP\dir

使用RMDir/r $INSTDIR in the uninstaller is not safe though it is unlikely
因为如果用户指定 $INSTDIR 是 Program Files时,可能导致整个文件夹被删除
Solutions are available for easily uninstalling only files which were installed by the installer.

9. SetOutPath outpath
Sets the output path($OUTDIR) and creates it if it does not exist,must be a full pathname,usually is just $INSTDIR
you can specify $INSTDIR if you are lazy with a single “-”
Registry,INI,File Instructions

10. DeleteINISec ini_filename section_name
Deletes the entire section [section_name] from ini_filename.If the section could not be removed from te ini file,
the error flag is set,it does not set the error flag if the section could not be found

WriteINIStr $TEMP\something.ini section1 something 123
WriteINIStr $TEMP\something.ini section1 somethingelse 1234
WriteINIStr $TEMP\something.ini section2 nsis true
DeleteINISec $TEMP\something.ini section1

11. DeleteINIStr ini_filename section_name str_name

WriteINIStr $TEMP\something.ini section1 something 123
DeleteINIStr $TEMP\something.ini section1 something

12. DeleteRegKey [/ifempty] root_key subkey
Deletes a registry key
if /ifempty is specified,the registry key will only be deleted if it has no subkeys
root_key valid value:

13. DeleteRegValue root_key subkey key_name

Deletes a registry value.

DeleteRegValue HKLM “Software\My Company\My Software” “some value”

14. EnumRegKey user_var(output) root_key subkey index
Set user variable $x with the name of the ‘index’th registry key in root_key\Subkey.
Returns an empty string if there are no more keys

15. EnumRegValue user_var(output) root_Key subkey index

16. ExpandEnvStrings user_var(output) string
Expands environment variables in string into the user variable $x,if an environment variable doesn’t exist,it will not be
replaced. For example,if you use “%var%” and var doesn’t exists,the result will be “%var”

ExpandEnvStrings $0 “WINDIR=%WINDIR%$\nTEMP=%TEMP%”

17. FlushINI ini_filename
Flushes the INI file’s buffers
causes the changes to be written to the disk immediately

WriteINIStr $TEMP\something.ini test test test
FlushINI $TEMP\something.ini

18. ReadEnvStr user_var(output) name
Reads from te environment string “name” and sets the value into the user variable $x

ReadEnvStr $0 WINDIR
ReadEnvStr $1 TEMP

19. ReadINIStr user_var(output) ini_filename section_name entry_name

© 版权声明
点赞0 分享
评论 抢沙发