Poprzedni | Spis treści | Następny

Rozdział 4: Skrypty


4.1 Format Pliku Skryptu

Plik Skryptu NSIS (.nsi) jest normalnym plikiem tekstowym z kodem skryptu.

Polecenia

Linie komend mają format 'polecenie [parametry]'

File "mójplik"

Komentarze

Linie zaczynające się znakiem ; lub # są komentarzem. Możesz wstawiać komentarze za poleceniami. Możesz również używać komentarzy w stylu języka C, aby skomentować jedną lub więcej lini kodu.


; Komentarz
# Komentarz

# Komentarz \
    Kolejna linia komentarza (zobacz poniżej na sekcję `Długie komentarze`)

/*
Komentarz
Komentarz
*/

Name /* komentarz */ mójinstalator

File "mójplik" ; Komentarz

Jeśli chcesz wstawić parametr poprzedzony znakiem ; lub # umieść go w cudzysłowiu.

Wtyczki

Aby wywołać wtyczkę, użyj składni 'wtyczka::polecenie [parametry]'. Więcej informacji znajdziesz tutaj: Wtyczki DLL.

nsExec::Exec "mójplik"

Liczby

W parametrach, które traktowane są jako liczby, użyj liczb dziesiętnych (liczba) lub liczb szesnastkowych (z poprzedzającym 0x, np. 0x12345AB), lub liczb ósemkowych (liczby zaczynające się od 0 bez x).

Kolory powinny być zapisywane w szesnastkowym formacie RGB, tak jak w HTML, ale bez znaku #.

IntCmp 1 0x1 lbl_equal

SetCtlColors $HWND CCCCCC

Łańcuchy Znaków

W łańcuchach znaków, które zawierają spacje, używaj cudzysłowiów:

MessageBox MB_OK "Witaj!"

Cudzysłowy mają tę właściwość, że zawierają parametr, jeśli zaczynają parametr. Mogą być one zarówno pojedynczymi znakami cudzysłowia, podwójnymi znakami cudzysłowia lub lewym pojedynczym cudzysłowiem.

Możesz ominąć cudzysłów poprzez użycie znaku $\:

MessageBox MB_OK "Będę ' szczęśliwy" ; wstawia ' do łańcucha znaków
MessageBox MB_OK 'Powiedział do mnie "Cześć!"' ; wstawia " do łańcucha znaków
MessageBox MB_OK `Powiedział do mnie "Będę ' szczęśliwy!"` ; wstawia znak ' jak i " do łańcucha znaków
MessageBox MB_OK "$\"Cudzysłów od mądrego człowieka$\" powiedział mądry człowiek" ; pomijamy cudzysłów

Możliwe jest też wstawianie do łańcuchów znaków nowych lini, znaku tabulatora itp., poprzez użycie $\r, $\n, $\t itp. Więcej informacji znajdziesz tutaj: Stałe Używane w Łańcuchach Znaków

Zmienne

Zmienne zaczynaja się znakiem $. Zmienne użytkownika powinny być zadeklarowane.

Var MYVAR
StrCpy $MYVAR "mojawartosc"

Więcej infomacji...

Długie polecenia

Aby rozszerzyć polecenie na wiele lini, użyj znaku ukośnika odwrotnego (\) na końcu lini. Następna linia zostanie dołączona do końca poprzedniej. Na przykład:

CreateShortCut "$SMPROGRAMS\NSIS\ZIP2EXE project workspace.lnk" \
    "$INSTDIR\source\zip2exe\zip2exe.dsw"

MessageBox MB_YESNO|MB_ICONQUESTION \
    "Czy chcesz usunąć wszystkie pliki z folderu? \
    (Jeśli masz jakikolwiek plik, który utworzyłeś i chcesz \
      go zachować, kliknij Nie)" \
    IDNO NoRemoveLabel

Rozszerzanie lini w długich poleceniach działa również w komentarzach. Może być to trochę mylące, więc lepiej tego unikać.

# Komentarz \
    a tutaj wciąż komentarz...

Plik konfiguracyjny

Jeśli plik o nazwie "nsisconf.nsh" istnieje w katalogu konfiguracji, zostanie dołączony domyślnie, przed jakimkolwiek skryptem (chyba że, użyty zostanie przełącznik lini poleceń /NOCONFIG). Katalog konfiguracji w Windows jest tym samym, w którym znajdują się plik makensis.exe. Na innych platformach ustawiane jest to przy instalacji i domyślnie jest to $PREFIX/etc/. Możesz zmienić to w czasie uruchomienia, więcej informacji znajdziesz tutaj: Zmienne Środowiskowe.


4.2 Zmienne

Wszystkie zmienne są zmiennymi globalnymi i mogą być użyte w Sekcjach oraz Funkcjach. Zauważ że, domyślnie, zmienne są ograniczone do 1024 znaków. Aby zwiększyć tę granicę, Zbuduj NSIS z większą wartością NSIS_MAX_STRLEN lub użyj wydania specjalnego NSIS.

4.2.1 Zmienne Użytkownika

$VARNAME

Zmienne użytkownika mogą być deklarowane poleceniem Var. Tych zmiennych możesz używać do przechowywania wartości, manipulowania łańcuchami znaków itd.

4.2.1.1 Var

[/GLOBAL] nazwa_zmiennej

Deklaracja zmiennej użytkownika. Dozwolone znaki dla nazw zmiennych: [a-z][A-Z][0-9] oraz '_'. Wszystkie zdefiniowane zmienne są zmiennymi globalnymi, nawet jeśli zostały zdefiniowane w sekcji lub funkcji. Dla jasności, zmienne zdefiniowane w sekcji lub funkcji muszą być użyte z flagą /GLOBAL. Flaga /GLOBAL nie jest wymagana poza sekcjami lub funkcjami.

Var przyklad

Function testVar
  Var /GLOBAL przyklad2

  StrCpy $przyklad "wartość przykładowa"
  StrCpy $przyklad2 "inna wartość przykładowa"
FunctionEnd

4.2.2 Inne Zapisywalne Zmienne

$0, $1, $2, $3, $4, $5, $6, $7, $8, $9, $R0, $R1, $R2, $R3, $R4, $R5, $R6, $R7, $R8, $R9

Rejestry. Zmienne te mogą być używane tak jak zmienne użytkownika, ale zazwyczaj używane są w współdzielonych funkcjach lub makrach. Nie musisz ich deklarować, więc nie ma ryzyka konfliktu nazw podczas ich używania w współdzielonym kodzie. Używając ich w kodzie współdzielonym, zaleca się używanie stosu, w celu zapisu i odzyskiwania ich oryginalnych wartości. Zmienne te mogą być również użyte do komunikacji z wtyczkami, ponieważ mogą być odczytywane i zapisywane przez wtyczki DLL.

$INSTDIR

Katalog instalacji ($INSTDIR może być zmieniony poprzez StrCpy, ReadRegStr, ReadINIStr, itd. - Może być użyty, na przykład, w funkcji .onInit, do bardziej zaawansowanej detekcji lokalizacji instalacji).

Zauważ, że w kodzie deinstalatora, $INSTDIR zawiera katalog, w którym znajduje się deinstalator. Nie koniecznie zawiera tę sama wartość, co w instalatorze. Na przykład, jeśli zapiszesz deinstalatora do $WINDIR i użytkownik go nie przeniesie, $INSTDIR będzie $WINDIR w deinstalatorze. Jeśli zapiszesz deinstalator do innego katalogu, powinieneś przechować $INSTDIR instalatora w rejestrze (lub w inny sposób) i następnie odczytać tę wartość w deinstalatorze.

$OUTDIR

Bieżący katalog wyjściowy (ustawiany poprzez SetOutPath lub StrCpy, ReadRegStr, ReadINIStr, itd.)

$CMDLINE

Linia poleceń instalatora. Format lini poleceń może być jednym z poniższych:

  • "pełna\ścieżka dostępu do\installer.exe" PARAMETR PARAMETR PARAMETR
  • installer.exe PARAMETR PARAMETR PARAMETR
  • O parsowaniu części z PARAMETRAMI, czytaj o funkcji GetParameters w dodatku użytecznych funkcji. Jeśli określono przełącznik lini poleceń /D= (zamiana katalogu instalacji) nie pokaże się w $CMDLINE.

$LANGUAGE

Identyfikator obecnie używanego języka. Na przykład, Angielski to 1033. Możesz zmienić tę zmienną w sekcji .onInit.

4.2.3 Stałe

Stałe mogą być również używane w atrybucie InstallDir.

Zauważ, że niektóre z nowych stałych nie będą poprawnie pracować w niektórych systemach operacyjnych. Na przykład, $CDBURN_AREA będzie działać tylko na Windows XP i nowszych. Jeśli zostanie użyta w systemie Windows 98, będzie pusta. Poza tymi oznaczonymi, stałe powinny być dostępne w każdym systemie operacyjnym.

$PROGRAMFILES

Katalog z zainstalowanymi programami (Program Files, zazwyczaj C:\Program Files, ale wykrywany w czasie wykonania).

$COMMONFILES

Katalog z plikami wspólnymi (Common Files). Jest to katalog, w którym przechowywane sa elementy współdzielone przez różne aplikacje (zazwyczaj C:\Program Files\Common Files, ale wykrywany w czasie wykonania). $DESKTOP

$DESKTOP

Katalog pulpitu windows (zazwyczaj C:\windows\desktop, ale wykrywany w czasie wykonania). Kontekst tej stałej (Wszyscy Użytkownicy (All Users) lub Bieżący Użytkownik (Current user)) zależny jest od ustawienia SetShellVarContext. Domyślnym jest bieżący użytkownik.

$EXEDIR

Lokalizacja pliku wykonywalnego instalatora (teoretycznie możesz modyfikować tę zmienną, ale nie jest to dobry pomysł).

${NSISDIR}

Symbol, który zawiera scieżkę dostępu do katalogu, w którym zainstalowany jest NSIS. Użyteczny, w przypadku potrzeby wywołania zasobów, które znajdują się w katalogu NSIS, np.Ikony, biblioteki Interfejsów Użytkownika (UI) itp.

Gdy instalator skompilowany jest z ustawieniem przechowywania makensis oraz danych w tym samym katalogu (domyślnie w Windows), jest tą sama lokalizacją dla makensis, na innych platformach zaś ustawiana w czasie kompilacji (więcej informacji w pliku INSTALL). W obu przypadkach możesz modyfikować to w czsie wykonania, ustawiając zmienną środowiskową NSISDIR. Więcej informacji znajdziesz tutaj: Zmienne Środowiskowe.

$WINDIR

Katalog Windows (zazwyczaj C:\windows lub C:\winnt, ale wykrywany w czasie wykonania).

$SYSDIR

Katalog systemowy windows (zazwyczaj C:\windows\system or C:\winnt\system32, ale wykrywany w czasie wykonania).

$TEMP

Systemowy katalog tymczasowy (zazwyczaj C:\windows\temp, ale wykrywany w czasie wykonania).

$STARTMENU

Katalog Menu Start (zazwyczaj w połączeniu z funkcją dodawania wpisów do menu CreateShortCut). Kontekst tej stałej (Wszyscy Użytkownicy lub Bieżący Użytkownik) zależny jest od ustawienia SetShellVarContext. Domyślnym jest bieżący użytkownik.

$SMPROGRAMS

Katalog programów Menu Start (użyj jeśli chcesz wykorzystać $STARTMENU\Programs). Kontekst tej stałej (Wszyscy Użytkownicy lub Bieżący Użytkownik) zależny jest od ustawienia SetShellVarContext. Domyślnym jest bieżący użytkownik.

$SMSTARTUP

Katalog Autostart / Programy Menu Start. Kontekst tej stałej (Wszyscy Użytkownicy lub Bieżący Użytkownik) zależny jest od ustawienia SetShellVarContext. Domyślnym jest bieżący użytkownik.

$QUICKLAUNCH

Folder szybkiego uruchamiania, dla Aktywnego Pulpitu IE4 i nowszych. Jeśli szybkie uruchamianie nie jest dostępne, zwraca tę samą wartość co $TEMP.

$DOCUMENTS

Katalog dokumentów. Typowa ścieżka dla bieżącego użytkownika to: C:\Documents and Settings\NazwaUżytkownika\Moje Dokumenty. Kontekst tej stałej (Wszyscy Użytkownicy lub Bieżący Użytkownik) zależny jest od ustawienia SetShellVarContext. Domyślnym jest bieżący użytkownik.

Stała ta nie jest dostępna w Windows 95 z niezainstalowanym Internet Explorer 4.

$SENDTO

Katalog, który zawiera skróty wpisów menu Wyślij do.

$RECENT

Katalog, który zawiera skróty do ostatnio używanych dokumentów użytkownika.

$FAVORITES

Katalog, który zawiera skróty do ulubionych stron internetowych, dokumentów itp. Kontekst tej stałej (Wszyscy Użytkownicy lub Bieżący Użytkownik) zależny jest od ustawienia SetShellVarContext. Domyślnym jest bieżący użytkownik.

Stała nie jest dostepna w Windows 95 z niezainstalowanym Internet Explorer 4.

$MUSIC

Katalog Moja Muzyka z plikami muzyki użytkownika. Kontekst tej stałej (Wszyscy Użytkownicy lub Bieżący Użytkownik) zależny jest od ustawienia SetShellVarContext. Domyślnym jest bieżący użytkownik.

Stała dostępna jest w Windows XP, ME i nowszych.

$PICTURES

Katalog Moje Obrazy z plikami obrazków użytkownika. Kontekst tej stałej (Wszyscy Użytkownicy lub Bieżący Użytkownik) zależny jest od ustawienia SetShellVarContext. Domyślnym jest bieżący użytkownik.

Stała dostępna jest w Windows 2000, XP, ME i nowszych.

$VIDEOS

Katalog z plikami Wideo użytkownika. Kontekst tej stałej (Wszyscy Użytkownicy lub Bieżący Użytkownik) zależny jest od ustawienia SetShellVarContext. Domyślnym jest bieżący użytkownik.

Stała dostępna jest w Windows XP, ME i nowszych.

$NETHOOD

Katalog, który zawiera obiekty, które mogą istnieć w katalogu Otoczenie Sieciowe/Cała sieć.

Stała ta nie jest dostępna w Windows 95 z niezainstalowanym Internet Explorer 4 oraz Aktywnym Pulpitem.

$FONTS

Systemowy katalog Czcionek.

$TEMPLATES

Katalog z Szablonami dokumentów. Kontekst tej stałej (Wszyscy Użytkownicy lub Bieżący Użytkownik) zależny jest od ustawienia SetShellVarContext. Domyślnym jest bieżący użytkownik.

$APPDATA

Katalog Danych Aplikacji. Wykrywanie ścieżki bieżącego użytkownika wymaga Internet Explorer 4 lub nowszego. Wykrywanie ścieżki wszystkich użytkowników wymaga Internet Explorer 5 lub nowszego. Kontekst tej stałej (Wszyscy Użytkownicy lub Bieżący Użytkownik) zależny jest od ustawienia SetShellVarContext. Domyślnym jest bieżący użytkownik.

Stała ta nie jest dostępna w Windows 95 z niezainstalowanym Internet Explorer 4 oraz Aktywnym Pulpitem.

$LOCALAPPDATA

Lokalny katalog Danych Aplikacji (nonroaming).

Stała ta dostępna jest w Windows 2000 i nowszych.

$PRINTHOOD

Katalog, który zawiera obiekty, które mogą istnieć w katalogu Drukarki.

Stała ta nie jest dostępna w Windows 95 oraz Windows 98.

$INTERNET_CACHE

Katalog Plików Tymczasowych Internet Explorera.

Stała ta nie jest dostępna w Windows 95 oraz Windows NT z niezainstalowanym Internet Explorer 4 oraz Aktywnym Pulpitem.

$COOKIES

Katalog plików Cookie Internet Explorera.

Stała ta nie jest dostępna w Windows 95 oraz Windows NT z niezainstalowanym Internet Explorer 4 oraz Aktywnym Pulpitem.

$HISTORY

Katalog Histori Internet Explorera.

Stała ta nie jest dostępna w Windows 95 oraz Windows NT z niezainstalowanym Internet Explorer 4 oraz Aktywnym Pulpitem.

$PROFILE

Katalog Profilu użytkownika. Typową ścieżką jest: C:\Documents and Settings\NazwaUżytkownika.

Ta stała dostępna jest w Windows 2000 i nowszych.

$ADMINTOOLS

Katalog z Narzędziami Administratora. Kontekst tej stałej (Wszyscy Użytkownicy lub Bieżący Użytkownik) zależny jest od ustawienia SetShellVarContext. Domyślnym jest bieżący użytkownik.

Stała ta dostępna jest w Windows 2000, ME i nowszych.

$RESOURCES

Katalog z Zasobami, w którym przechowywame są schematy i inne zasoby Windows (zazwyczaj C:\Windows\Resources, ale wykrywane w czasie wykonywania).

Ta stała dostępna jest w Windows XP i nowszych.

$RESOURCES_LOCALIZED

Katalog Zlokalizowanych Zasobów, w którym przechowywane są schematy i inne zasoby (zazwyczaj C:\Windows\Resources\1033, ale wykrywane w czasie wykonywania).

Ta stała dostępna jest w Windows XP i nowszych.

$CDBURN_AREA

Katalog, w którym przechowywane są pliki czekające na wypalenie na CD.

Ta stała dostępna jest w Windows XP i nowszych.

$HWNDPARENT

Liczba dziesiętna uchwytu HWND okna rodzica.

$PLUGINSDIR

Ścieżka do folderu tymczasowego, tworzonego przy pierwszym użyciu wtyczki lub wywołaniu InitPluginsDir. Folder ten jest automatycznie usuwany po zamknięciu instalatora. Jest on idealnym miejscem na przechowywanie plików INI dla InstallOptions bitmap wtyczek lub dowolnych innych plików, które są wymagane do działania wtyczki.

4.2.4 Stałe Używane w Łańcuchach Znaków

$$

Użyj do wyświetlenia znaku $.

$\r

Użyj do wyświetlenia znaku przeniesienia do nowej lini (\r).

$\n

Użyj do wyświetlenia znaku nowej lini (\n).

$\t

Użyj do wyświetlenia znaku tabulacji (\t).


4.3 Etykiety

Etykiety są miejscem w kodzie, do którego przenosi nas instrukcja Goto, lub innych instrukcji wymagających rozgałęzienia (takich jak IfErrors, MessageBox, IfFileExists oraz StrCmp). Etykiety muszą znajdować się w Sekcji lub Funkcji. Etykiety mają zasięg lokalny, co oznacza, że są one dostępne tylko w ramach Sekcji lub Funkcji, w których zostały utworzone. Aby zadeklarować Etykietę, po prostu użyj zapisu:

MojaEtykieta:

Etykiety nie mogą rozpoczynać się znakami -, +, !, $, lub 0-9. Określając etykiety dla różnych instrukcji, które je wymagają, pamiętaj, że zarówno pusty łańcuch znaków ("") jak i 0 reprezentują następną instrukcję (co oznacza, że nie wystąpi Goto). Etykiety rozpoczynające się znakiem kropki(.) są etykietami globalnymi, co oznacza, że możesz przejść do nich z dowolnej funkcji lub sekcji (jednak nie możesz przeskoczyć do globalnej etykiety deinstalatora z instalatora i na odwrót).


4.4 Skoki Warunkowe

W przeciwieństwie do etykiet, skoki warunkowe są, jak sugeruje nazwa, zależne od miejsca, z którego zostały wywołane. Możesz używać skoków warunkowych tam gdzie etykiet. Skoki warunkowe oznaczane są przez liczby. +1 oznacza przeskok do następnej instrukcji (domyśln krok), +2 przeskoczy jedną instrukcję i przejdzie do drugiej instrukcji po bieżącej, -2 przeskoczy dwie instrukcje wstecz, a +10 przeskoczy 9 instrukcji, przechodząc do instrukcji dziesiątej po bieżącej.

Instrukcja jest każdym poleceniem, które jest realizowane w czasie wykonania, gdy uruchomiony jest instalator. Wszystkie przykładowo wymienione polecenia MessageBox, Goto, GetDLLVersion, FileRead, SetShellVarContext są instrukcjami. Inne polecenia, to jest AddSize, Section, SectionGroup, SectionEnd, SetOverwrite (i wszystkie po Flagi Kompilatora), Name, SetFont, LangString nie są instrukcjami, ponieważ wykonywane są one w czasie kompilacji.

Przykłady:

 Goto +2
   MessageBox MB_OK "Nigdy nie zobaczysz tego komunikatu"
 MessageBox MB_OK "Poprzedni komunikat został pominięty, ten powinien zostać wyświetlony"
 Goto +4
 MessageBox MB_OK "Następny komunikat zostanie pominięty"
 Goto +3
 MessageBox MB_OK "Nigdy nie zobaczysz tego komunikatu"
 Goto -3
 MessageBox MB_OK "OK"

Zauważ, że polecenie wstawiania makra nie jest rozważane jako jedna instrukcja, w sytuacji skoku warunkowego. Przed zastosowaniem skoku warunkowego makro jest rozwijane, więc skoki warunkowe mogą przeskoczyć do wnętrza kodu wstawianego makra. Poniższy, przykładowy kod, nie pominie makra. Wyświetli komunikat.

!macro relative_jump_test
  MessageBox MB_OK "Pierwsza linia makra"
  MessageBox MB_OK "Druga linia makra"
!macroend

Goto +2
!insertmacro relative_jump_test

4.5 Strony

Każdy instalator NSIS (okienkowy) posiada zbiór stron. Każda strona może być stroną wbudowaną w NSIS lub własną stroną, utworzoną przez funkcje użytkownika (poprzez użycie na przykład wtyczki InstallOptions).

Używając skryptu, możesz kontrolować kolejność wywoływania stron, ich wygląd oraz zachowanie. Możesz pomijać strony, nadawać im kolor (np. biały), wymuszać na użytkowniku pozostanie na stronie dopóki nie spełniony zostanie określony warunek, wyświetlać stronę Czytaj mnie, wyświetlać własne zaprojektowane strony do wprowadzania danych oraz więcej. W tej sekcji, nauczysz się w jaki sposób kontrolować wszystko co zostało wymienione powyżej.

Istnieją dwa podstawowe polecenia związane ze stronami, Page oraz UninstPage. Pierwsze z nich dodaje stronę do instalatora, druga zaś dodaje stronę do deinstalatora. Istnieje również polecenie PageEx, które pozwala na dodanie strony z większą ilością opcji. PageEx pozwala na ustawienie opcji do określonej strony,zamiast używania domyślnego zbioru, który ustawiany jest poza PageEx.

4.5.1 Kolejność Wywoływań

Kolejność wywoływania stron ustalany jest po prostu poprzez zapis poleceń Page, UninstPage oraz PageEx w skrypcie w żądanej kolejności. Na przykład:

 Page license
 Page components
 Page directory
 Page instfiles
 UninstPage uninstConfirm
 UninstPage instfiles

Powyższy kod instruuje NSIS, by najpierw wyświetlona została strona z postanowieniami licencji, nastepnie strona z wyborem komponentów do zainstalowania, nastepnie strona wyboru katalogu instalacji oraz w końcu strona z oknem logu, na której wykonywane są poszczególne sekcje, tak jak w starszych instalatorach. Deinstalator wyświetli wpierw stronę z potwierdzeniem deinstalacji oprogramowania i następnie stronę logu z postępem deinstalacji.

Możesz określić typ tej samej strony kilka razy.

Aby zapewnić kompatybilność wsteczną z starszymi skryptami NSIS, następujące strony instalatora zostaną dodane, jeśli nie użyto żadnych poleceń wywoływania stron: license (jeśli LicenseText oraz LicenseData zostały określone), components (jeśli ComponentText został określony i jest więcej niż jedna widoczna sekcja), directory (jeśli DirText został określony) oraz instfiles. Gdy nie użyto zadnych poleceń wywoływania stron deinstalatora, następujace strony zostaną dodane: strona potwierdzenia deinstalacji (jeśli UninstallText został określony) oraz instfiles. Metoda ta jest obecnie odradzana, zaleca się konwersję skryptów do takich, które używają poleceń wywoływania stron, ponieważ możesz użyć nowego standardu językowych łańcuchów znaków.

4.5.2 Opcje Strony

Każda strona ma swój unikalny zestaw danych, które definiują ich wygląd oraz działanie. W tej sekcji zostaną opisane, które dane poszczególnych stron są używane i w jaki sposób możesz je ustawiać. Funkcje zwrotne opisane są poniżej i w tej sekcji nie ma do nich odniesień.

Poniższa lista wypisuje polecenia, które mają wpływ na każdą z typu stron. Jeśli nie napisano inaczej, komendy te mogą być używane zarówno w jak i poza blokiem PageEx. Jeśli używane są wewnątrz bloku PageEx, będą one miały wpływ tylko na bieżącą stronę, ustawianą przez PageEx, w przeciwnym razie zaś ustawia one domyślne ustawienia dla każdej z innych stron.

Strona z postanowieniami Licencji

Strona wyboru komponentów

Strona wyboru katalogu docelowego

Strona logu De/Instalacji

Strona potwierdzająca deinstalację

Aby ustawić tekst w nagłówku strony użyj polecenia Caption.

4.5.3 Funkcje zwrotne (Callbacks)

Każda wbudowana strona posiada trzy funkcje zwrotne: Przed-funkcja, Funkcja wyświetlania-tworzenia oraz funkcja zamykania. Funkcja Przed-funkcja jest wywoływana tuż przed utworzeniem strony, funkcja wyświetlania-tworzenia jest wywoływana tuż po utworzeniu oraz funkcja zamykania jest wywoływana tuż po naciśnieciu przez użytkownika przycisku Dalej i przed jej zamknięciem.

  • Przed-funkcja pozwala na pominiecie strony poprzez użycie polecenia Abort.
  • Funkcja wyświetlania pozwala na ulepszenie interfejsu użytkownika strony poprzez użycie poleceń CreateFont, SetCtlColors, SendMessage i innych.
  • Funkcja zamykania pozwala na wymuszenie na użytkowniku pozostania na bieżącej stronie poprzez użycie polecenia Abort.

Własne strony posiadają tylko dwie funkcje zwrotne, jedną, która tworzy tę stronę (wymagana) oraz drugą - funkcję zamykania, która działa tak jak ta w stronach wbudowanych.

Przykłady:

 Page license skipLicense "" stayInLicense
 Page custom customPage "" ": custom page"
 Page instfiles

 Function skipLicense
   MessageBox MB_YESNO "Czy chcesz pominąć stronę z postanowieniami licencji?" IDNO no
     Abort
   no:
 FunctionEnd

 Function stayInLicense
   MessageBox MB_YESNO "Czy chcesz pozostać na stronie z postanowieniami licencji?" IDNO no
     Abort
   no:
 FunctionEnd

 Function customPage
   GetTempFileName $R0
   File /oname=$R0 customPage.ini
   InstallOptions::dialog $R0
   Pop $R1
   StrCmp $R1 "cancel" done
   StrCmp $R1 "back" done
   StrCmp $R1 "success" done
   error: MessageBox MB_OK|MB_ICONSTOP "Błąd InstallOptions:$\r$\n$R1"
   done:
 FunctionEnd

4.5.4 Page

custom [creator_function] [leave_function] [caption] [/ENABLECANCEL]
  LUB
internal_page_type [pre_function] [show_function] [leave_function] [/ENABLECANCEL]

Dodaje stronę do instalatora. Więcej informacji znajdziesz w sekcji powyżej, opisującej wbudowane strony i strony własne oraz funkcje zwrotne.

internal_page_type może być:

  • license - strona z postanowieniami licencji
  • components - strona wyboru komponentów do zainstalowania
  • directory - strona wyboru katalogu docelowego instalacji
  • instfiles - strona instalacji, na której wykonywane są sekcje
  • uninstConfirm - strona potwierdzająca deinstalację

Ostatnia strona instalatora ma przycisk Anuluj zablokowany, aby uniknąć ewentualnej pomyłki. Aby go aktywować, użyj polecenia /ENABLECANCEL.

4.5.5 UninstPage

custom [creator_function] [leave_function] [caption] [/ENABLECANCEL]
  LUB
internal_page_type [pre_function] [show_function] [leave_function] [/ENABLECANCEL]

Dodaje stronę deinstalatora. Więcej informacji znajdziesz w sekcji powyżej, opisującej wbudowane strony i strony własne oraz funkcje zwrotne.

O możliwych wartościach internal_page_type czytaj tutaj: Page.

4.5.6 PageEx

[un.](custom|uninstConfirm|license|components|directory|instfiles)

Dodaje stronę do instalatora lub deinstalatora (jeśli z przedrostkiem un.). Każda strona PageEx musi mieć odpowiadający jej PageExEnd. W bloku PageEx możesz ustawiać opcje, które są specyficzne dla danej strony i które nie zostaną użyte w innych. Opcje, które nie zostaną użyte przyjmą ustawienia z poza bloku PageEx lub domyślne, jeśli nic nie ustawiono. Aby ustalić opisy w nagłówku strony użyj poleceń Caption lub SubCaption. Aby ustalić funkcje zwrotne w PageEx użyj PageCallbacks. Więcej informacji o wbudowanych stronach i własnych znajdziesz w powyższych sekcjach.

Przykładowe użycie:

 PageEx license
   LicenseText "Readme"
   LicenseData readme.rtf
 PageExEnd

 PageEx license
   LicenseData license.txt
   LicenseForceSelection checkbox
 PageExEnd

4.5.7 PageExEnd

Zamyka blok PageEx.

4.5.8 PageCallbacks

([creator_function] [leave_function]) | ([pre_function] [show_function] [leave_function])

Ustawia funkcje zwrotne dla strony zdefiniowanej przez PageEx. Może być użyte tylko we wnetrzu bloku PageEx. Więcej informacji znajdziesz powyżej, w opisie funkcji zwrotnych.

PageEx license
  PageCallbacks licensePre licenseShow licenseLeave
PageExEnd

4.6 Sekcje

Każdy instalator NSIS posiada jedną lub więcej sekcji. Każda z tych sekcji jest tworzona, modyfikowana i zamykana przy użyciu następujących poleceń.

  • Każda sekcja zawiera zero lub więcej instrukcji.
  • Sekcje wykonywane są w kolejności przez wynikowy instalator oraz jeśli ComponentText jest ustawiony, użytkownik będzie miał opcje wyłączenia/włączenia każdej widocznej sekcji.
  • Jeśli nazwą sekcji jest 'Uninstall' lub rozpoczyna się prefiksem 'un.', jest to sekcja deinstalatora.

4.6.1 Polecenia Funkcji

4.6.1.1 AddSize

rozmiar_kb

Instruuje instalatora, poprzez podanie rozmiaru "rozmiar_kb", że bieżąca sekcja wymaga dodatkowego miejsca na dysku. Tylko wewnątrz sekcji (nie odniesie skutku poza sekcją lub w funkcji).

Section
AddSize 500
SectionEnd

4.6.1.2 Section

[/o] [([!]|[-])section_name] [section_index_output]

Otwiera nową sekcję. Jeśli section_name jest pusta, pominięta lub zaczynajaca się znakiem -, to jest to sekcja ukryta i użytkownik nie bedzie miał opcji jej wyłączenia. Jeśli nazwą sekcji jest 'Uninstall' lub jest poprzedzona prefiksem 'un.', to jest to sekcja deinstalatora. Jeśli section_index_output jest określony, parametr będzie zdefiniowany (!defined) indeksem sekcji (może być użyte dla SectionSetText itp.). Jeśli nazwa sekcji zaczyna się znakiem !, sekcja zostanie wyświetlona pogrubioną czcionką. Jeśli określony jest przełącznik /o, sekcja będzie domyślnie odznaczona.

Section "-ukryta sekcja"
SectionEnd

Section # ukryta sekcja
SectionEnd

Section "!pogrubiona sekcja"
SectionEnd

Section /o "opcjonalna"
SectionEnd

Section "instalacja czegoś" SEC_IDX
SectionEnd

Aby uzyskać dostęp do indeksu sekcji, musi być użyty nawias klamrowy i kod musi znajdować się poniżej sekcji w skrypcie.

Section test1 sec1_id
SectionEnd

Section test2 sec2_id
SectionEnd

Function .onInit
  SectionGetText ${sec2_id} $0
  MessageBox MB_OK "Nazwa ${sec2_id}:$\n$0" # wyświetli 'Nazwa 1: test2'
FunctionEnd
Function .onInit
  SectionGetText ${sec2_id} $0
  MessageBox MB_OK "Nazwa ${sec2_id}:$\n$0" # wyświetli 'Nazwa ${sec2_id}: test1'
    # plus ostrzeżenie:
    #   Wykryto nieznaną zmienną/stałą "{sec2_id}", ignorowana
FunctionEnd

Section test1 sec1_id
SectionEnd

Section test2 sec2_id
SectionEnd

4.6.1.3 SectionEnd

Polecenie zamyka bieżącą otwartą sekcję.

4.6.1.4 SectionIn

insttype_index [insttype_index] [RO]

Polecenie to określa, do którego typu instalacji (zobacz InstType) domyślnie należy bieżąca sekcja. Można określić również wiele poleceń SectionIn (są łączone). Jeśli określisz RO jako parametr, to sekcja będzie tylko do odczytu, zo oznacza, że użytkownik nie będzie mógł zmienić jej stanu. Pierwszy typ instalacji zdefiniowany poleceniem InstType jest indeksowany od 1, następny równy jest 2 i tak dalej.

InstType "Pełna"
InstType "Minimalna"

Section "Sekcja"
SectionIn 1 2
SectionEnd

Section "Inna sekcja"
SectionIn 1
SectionEnd

4.6.1.5 SectionGroup

[/e] section_group_name [index_output]

Polecenie to wstawia grupę sekcji. Grupa sekcji musi być zamknięta poleceniem SectionGroupEnd, oraz powinna zawierać jedną (1) lub więcej sekcji. Jeśli grupa sekcji zaczyna się znakiem !, nazwa tej grupy zostanie wyświetlona pogrubioną czcionką. Jeśli określono przełącznik /e, grupa sekcji bedzie domyślnie rozwinięta. Jeśli określono index_output, parametrem będzie !defined z indeksem sekcji (który może być użyty w SectionSetText etc). Jeśli nazwa grupy sekcji poprzedzona jest prefiksem 'un.', grupa sekcji jest grupą sekcji deinstalatora.

SectionGroup "Jakieś elementy"
Section "Sekcja"
SectionEnd
Section "Kolejna sekcja"
SectionEnd
SectionGroupEnd

4.6.1.6 SectionGroupEnd

Zamyka grupę sekcji otwartą poleceniem SectionGroup.

4.6.2 Sekcja Deinstalacji

Specjalna Sekcja o nazwie 'Uninstall' musi być utworzona, aby utworzyć deinstalatora. Sekcja ta powinna usuwać z systemu wszystkie pliki, klucze rejestru itd., które zostały zainstalowane przez instalatora. Poniżej znajduje się przykład prostej sekcji deinstalacji:

Section "Uninstall"
  Delete $INSTDIR\Uninst.exe ; usuwa się (poniżej znajduje się wyjaśnienie, jak to jest możliwe)
  Delete $INSTDIR\MójProgram.exe
  RMDir $INSTDIR
  DeleteRegKey HKLM SOFTWARE\MójProgram
SectionEnd

Pierwsza instrukcja, Delete działa (to jest usuwa deinstalatora), ponieważ deinstalator jest kopiowany w tle do tymczasowego katalogu systemu, dla deinstalacji.

Zauważ, że kod deinstalatora, $INSTDIR zawiera ścieżkę dostępu do katalogu, w którym znajduje się deinstalator. Niekoniecznie zawiera on tę samą wartość, która w tej samej zmiennej znajdowała się w instalatorze.


4.7 Funkcje

Funkcje są podobe do Sekcji, zawierając również zero lub więcej instrukcji. Funkcje użytkownika nie są bezposrednio wywoływane przez instalatora, ale wywoływane są z Sekcji, przy użyciu instrukcji Call. Funkcje Zwrotne wywoływane są przez instalatora, gdy wystąpi określone zdarzenie.

Funkcje muszą być zadeklarowana poza Sekcją lub inną Funkcją.

4.7.1 Polecenia Funkcji

4.7.1.1 Function

[nazwa_funkcji]

Zaczyna i otwiera nową funkcję. Nazwy funkcji, zaczynające się znakiem "." (np. ".Cokolwiek") są ogólnie zarezerwowane dla funkcji zwrotnych. Nazwy funkcji, zaczynające się przedrostkiem "un." określają funkcje, które zostana utworzone w Deinstalatorze. Na skutek tego, normalne sekcje instalatora oraz funkcje nie mogą wywoływać funkcji deinstalatora, oraz Sekcje Deinstalatora oraz funkcje deinstalatora nie mogą wywoływać normalnych funkcji.

Function func
  # jakieś polecenia
FunctionEnd

Section
  Call Funckja
SectionEnd

4.7.1.2 FunctionEnd

Polecenie to zamyka bieżącą otwartą funkcję.

4.7.2 Funkcje Zwrotne

Możesz tworzyć funkcje zwrotne, które mają specjalne nazwy, które będą wywoływane przez instalatora, w określonych miejscach instalacji. Poniżej znajduje się lista obecnie dostępnych funkcji zwrotnych:

4.7.2.1 Funkcje Zwrotne Instalacji

4.7.2.1.1 .onGUIInit

Ta funkcja zwrotna jest wywoływana tuż przed załadowaniem i wyświetleniem pierwszej strony, co pozwala na ulepszenie interfejsu użytkownika.

Przykład:

 !include "WinMessages.nsh"

 Function .onGUIInit
   # 1028 jest numerem id kontrolki z tekstem opisującym firmę (branding text)
   GetDlgItem $R0 $HWNDPARENT 1028
   CreateFont $R1 "Tahoma" 10 700
   SendMessage $R0 ${WM_SETFONT} $R1 0
   # ustaw kolor tła na biały oraz kolor tekstu na czerwony
   SetCtlColors $R0 FFFFFF FF0000
 FunctionEnd
4.7.2.1.2 .onInit

Ta funkcja zwrotna jest wywoływana, gdy instalator jest bliski zakończenia inicjalizacji. Jeśli funkcja '.onInit' wywoła polecenie Abort, instalator natychmiast zakończy działanie.

Ponizej znajdują się dwa przykłady, jak można jej użyć:

 Function .onInit
   MessageBox MB_YESNO "Ten program zainstaluje. Kontynuować?" IDYES NoAbort
     Abort ; powoduje zamknięcie instalatora.
   NoAbort:
 FunctionEnd

lub:

 Function .onInit
   ReadINIStr $INSTDIR $WINDIR\wincmd.ini Configuration InstallDir
   Pop $INSTDIR "" 0 NoAbort
     MessageBox MB_OK "Nie znaleziono programu Windows Commander. Nie udało się pobrać ścieżki instalacji."
     Abort ; powoduje zamknięcie instalatora.
   NoAbort:
 FunctionEnd
4.7.2.1.3 .onInstFailed

Ta funkcja zwrotna jest wywoływana, gdy użytkownik naciśnie przycisk 'Anuluj', gdy instalacja nie powiedzie się (jeśli nie uda się wyodrębnić pliku, lub skrypt instalatora użyje polecenia Abort).

Przykład:

  Function .onInstFailed
    MessageBox MB_OK "Życzę więcej szczęścia następnym razem."
  FunctionEnd
4.7.2.1.4 .onInstSuccess

Ta funkcja zwrotna jest wywoływana, gdy instalacja zakończy się sukcesem, tuż po zamknięciu okna instalacji (czyli po kliknięciu przez użytkownika na przycisk 'Zamknij', jeśli instrukcje AutoCloseWindow lub SetAutoClose są ustawione na fałsz (false)).

Przykład:

  Function .onInstSuccess
    MessageBox MB_YESNO "Gratulacje, udało się. Czy chcesz zobaczyć plik readme?" IDNO NoReadme
      Exec notepad.exe ; otwiera plik readme lub cokolwiek chcesz.
    NoReadme:
  FunctionEnd
4.7.2.1.5 .onGUIEnd

Ta funkcja zwrotna jest wywoływana tuż po zamknięciu okna instalatora. Użyj jej do zwolnienia pamięci wtyczek interfejsu, jeśli jest taka potrzeba.

4.7.2.1.6 .onMouseOverSection

Ta funkcja zwrotna jest wywoływana zawsze, gdy kursor myszy znajdujący się nad drzewem sekcji zmieni swoją pozycję. Pozwala to na ustawienie opisów dla każdej z sekcji, na przykład. Numer id sekcji, nad którym aktualnie znajduje się kursor myszy, przechowywany jest tymczasowowo w zmiennej $0.

Przykład:

  Function .onMouseOverSection
    FindWindow $R0 "#32770" "" $HWNDPARENT
    GetDlgItem $R0 $R0 1043 ; opis elementu (musi zostać uprzednio dodany do UI)

    Pop $0 0 "" +2
      SendMessage $R0 ${WM_SETTEXT} 0 "STR:Opis pierwszej sekcji"

    Pop $0 1 "" +2
      SendMessage $R0 ${WM_SETTEXT} 0 "STR:Opis drugiej sekcji"
  FunctionEnd
4.7.2.1.7 .onRebootFailed

Ta funkcja zwrotna jest wywoływana, jeśli funkcja Reboot nie powiedzie się. Polecenia WriteUninstaller, wtyczki, File oraz WriteRegBin nie powinny być używane w tej funkcji zwrotnej.

Przykład:

 Function .onRebootFailed
   MessageBox MB_OK|MB_ICONSTOP "Funkcja Reboot nie powiodła się. Zrestartuj komputer ręcznie." /SD IDOK
 FunctionEnd
4.7.2.1.8 .onSelChange

Ta funkcja zwrotna jest wywoływana, gdy zmienia się zaznaczenie na stronie komponentów. Użyteczna w połączeniu z instrukcjami SectionSetFlags oraz SectionGetFlags.

Zmiany zaznaczenie obejmują zarówno zaznaczenie sekcji jak i zmianę typu instalacji.

4.7.2.1.9 .onUserAbort

Ta funkcja zwrotna jest wywoływana, gdy użytkownik kliknie przycisk 'Anuluj', a instalacja jeszcze się nie nie powiodła. Jeśli ta funkcja wywoła funkcję Abort, instalacja nie zostanie przerwana.

Przykład:

 Function .onUserAbort
   MessageBox MB_YESNO "Przerwać instalację?" IDYES NoCancelAbort
     Abort ; zamyka instalatora.
   NoCancelAbort:
 FunctionEnd
4.7.2.1.10 .onVerifyInstDir

Ta funkcja zwrotna aktywuje kontrolkę, w zależności od tego czy ścieżka instalacji jest poprawna lub nie. Kod ten wywoływany jest za każdym razem, gdy użytkownik zmieni katalog instalacji, więc nie powinna robić niczego dziwnego w instrukcji MessageBox lub podobnej. Jeśli funkcja ta wywoła funkcję Abort, ścieżka instalacji w zmiennej $INSTDIR będzie uważana za nieprawidłową.

Przykład:

  Function .onVerifyInstDir
    IfFileExists $INSTDIR\Winamp.exe PathGood
      Abort ; jeśli $INSTDIR nie jest katalogiem Winampa, nie pozwól na instalację
    PathGood:
  FunctionEnd

4.7.2.2 Funkcje Zwrotne Deinstalacji

4.7.2.2.1 un.onGUIInit

Ta funkcja zwrotna jest wywoływana tuż przed załadowaniem i wyświetleniem pierwszej strony, co pozwala na ulepszenie interfejsu użytkownika deinstalatora.

Spójrz na przykład opisany w .onGUIInit.

4.7.2.2.2 un.onInit

Ta funkcja zwrotna jest wywoływana, gdy deinstalator jest bliski zakończenia inicjalizacji. Jeśli funkcja 'un.onInit' wywoła polecenie Abort, deinstalator natychmiast zakończy działanie. Zauważ, że funkcja ta może zweryfikować oraz/lub zmodyfikować zmienną $INSTDIR, jeśli jest taka potrzeba.

Poniżej znajdują się dwa przykłady, jak można jej użyć:

  Function un.onInit
    MessageBox MB_YESNO "Ten program odinstaluje. Kontynuować?" IDYES NoAbort
      Abort ; zamyka deinstalatora.
    NoAbort:
  FunctionEnd

lub:

  Function un.onInit
    IfFileExists $INSTDIR\mójplik.exe found
      MessageBox MB_OK "Ścieżka dostępu deinstalatora niepoprawna"
      Abort
    found:
  FunctionEnd
4.7.2.2.3 un.onUninstFailed

Ta funkcja zwrotna jest wywoływana, gdy użytkownik naciśnie przycisk 'Anuluj', gdy deinstalacja nie powiedzie się (jeśli użyto polecenia Abort lub z innego powodu nie powiedzie się).

Przykład:

  Function un.onUninstFailed
    MessageBox MB_OK "Życzę więcej szczęścia następnym razem."
  FunctionEnd
4.7.2.2.4 un.onUninstSuccess

Ta funkcja zwrotna jest wywoływana, gdy deinstalacja zakończy się sukcesem, tuż po zamknięciu okna deinstalacji (czyli po kliknięciu przez użytkownika na przycisk 'Zamknij', jeśli instrukcja SetAutoClose jest ustawiona na fałsz (false)).

Przykład:

  Function un.onUninstSuccess
    MessageBox MB_OK "Gratulacje, deinstalacja udała się."
  FunctionEnd
4.7.2.2.5 un.onGUIEnd

Ta funkcja zwrotna jest wywoływana tuż po zamknięciu okna deinstalatora. Użyj jej do zwolnienia pamięci wtyczek interfejsu, jeśli jest taka potrzeba.

4.7.2.2.6 un.onRebootFailed

Ta funkcja zwrotna jest wywoływana, jeśli funkcja Reboot nie powiedzie się. Polecenia WriteUninstaller, wtyczki, File oraz WriteRegBin nie powinny być używane w tej funkcji zwrotnej.

Przykład:

 Function un.onRebootFailed
   MessageBox MB_OK|MB_ICONSTOP "Funkcja Reboot nie powiodła się. Zrestartuj komputer ręcznie." /SD IDOK
 FunctionEnd
4.7.2.2.7 un.onUserAbort

Ta funkcja zwrotna jest wywoływana, gdy użytkownik kliknie przycisk 'Anuluj', a instalacja jeszcze się nie nie powiodła. Jeśli ta funkcja wywoła funkcję Abort, deinstalacja nie zostanie przerwana.

Przykład:

  Function un.onUserAbort
    MessageBox MB_YESNO "Przerwać deinstalację?" IDYES NoCancelAbort
      Abort ; zamyka deinstalatora.
    NoCancelAbort:
  FunctionEnd

4.8 Atrybuty Instalatora

4.8.1 Atrybuty Ogólne

Wszystkie poniższe polecenia ustawiają atrybuty instalatora. Atrybuty te kontrolują jego wygląd oraz zachowanie się - które strony będą wyświetlane oraz jakie teksty będą wyświetlane na każdej ze stron, jaka jest nazwa instalatora, jakiej ikony używa instalator, domyślny katalog instalacji, plik przez niego zapisywany i więcej. Pamiętaj, że te atrybuty mogą być ustawiane gdziekolwiek w pliku skryptu, poza Sekcją oraz Funkcją.

Domyślne wartości są pogrubione oraz podkreślone

4.8.1.1 AddBrandingImage

(left|right|top|bottom) (width|height) [padding]

Dodaje obrazek firmowy na górze, dole, po lewej lub po prawej stronie instalatora. Jego rozmiar ustawiany jest zgodnie z określonymi wartościami szerokości/wysokości (width/height), szerokości/wysokości instalatora oraz czcionki instalatora. Końcowy rozmiar nie zawsze będzie taki jak chciałeś; spojrzyj na wyjście polecenia, aby zobaczyć aktualny rozmiar. Dzieje się tak, ponieważ zależy to od czcionki instalatora, dlatego przed użyciem polecenia AddBrandingImage powinieneś użyć polecenia SetFont. Domyślną wartością odstępu (padding) jest 2.

Polecenie AddBrandingImage tylko dodaje miejsce na obrazek. Aby ustawić obrazek w czasie wykonania, użyj polecenia SetBrandimgImage.

AddBrandingImage left 100
AddBrandingImage right 50
AddBrandingImage top 20
AddBrandingImage bottom 35
AddBrandingImage left 100 5

4.8.1.2 AllowRootDirInstall

true|false

Kontroluje czy instalacja przeprowadzana jest do głównego katalogu dysku lub bezpośrednio do współdzielonej sieci. Ustaw wartość parametru na 'true', aby zmienić bezpieczne zachowanie, które uniemożliwia użytkownikowi wybranie lokalizacji typu C:\ lub \\Serwer\Share, jako katalog instalacji (i później, deinstalacji). Dodatkowe możliwości dostosowywania strony wyboru katalogu znajdziesz w .onVerifyInstDir.

4.8.1.3 AutoCloseWindow

true|false

Ustawia czy okno instalatora automatycznie jest zamykane po zakończeniu instalacji, czy też nie. Polecenie to można zmienić w sekcji przy użyciu polecenia SetAutoClose.

4.8.1.4 BGFont

[font_face [height [weight] [/ITALIC] [/UNDERLINE] [/STRIKE]]]

Określa czcionkę używaną do wyświetlania tekstu na gradientowym tle. Aby ustawić kolor, użyj polecenia BGGradient. Jeśli nie określono parametrów, użyta zostanie domyślna czcionka. Domyślną czcionką jest czcionka Times New Roman, pogrubiona oraz pochylona.

4.8.1.5 BGGradient

[off|(topc botc [textcolor|notext])]

Określa czy używać gradientowego tła okna, czy też nie. Jeśli wartość parametru ustawiono na 'off', instalator nie będzie wyświetlał okna tła, jeśli nie określono parametrów, użyty zostanie domyślny gradient z czerni do niebieskiego, w przeciwnym razie do utworzenia gradientu używane są kolory top_color lub bottom_color. Top_color oraz bottom_color określane są przy użyciu formatu RRGGBB (w zapisie szesnastkowym, jak w HTML, oprócz znaku poprzedzajacego '#', który używany jest do komentarza). Parametr 'textcolor' może być również określony, lub 'notext', co wyłączy tekst dużego tła.

4.8.1.6 BrandingText

/TRIM(LEFT|RIGHT|CENTER) text

Ustawia tekst, który wyświetlany jest u dołu okna instalacji (domyślnie tekstem tym jest 'Nullsoft Install System vX.XX'). Ustawiając ten tekst na pusty ("") sprawiamy, że używany jest domyślny; aby ustawić brak tekstu, użyj " " (spację). Jeśli nie jest to dla ciebie ważne, pozostaw tekst domyślny, zeby wszyscy wiedzieli dlaczego instalator działa dobrze. ;). Użyj parametrów /TRIMLEFT, /TRIMRIGHT lub /TRIMCENTER, aby obciąć rozmiar kontrolki do rozmiaru tekstu.

Akceptowane są zmienne. Jeśli używane są zmienne, muszą być one zainicjowane w sekcji .onInit.

4.8.1.7 Caption

caption

Gdy polecenie to używane jest poza blokiem PageEx: Ustawia tekst dla tytułu okna instalatora. Domyślnie tekstem tym jest 'Name Setup', gdzie nazwa Name jest określona przez instrukcję Name. Możesz jednak nadpisać to przez tekst 'Instalator mojej aplikacji' lub cokolwiek innego. Jeśli określisz pusty tekst (""), użyty zostanie domyślny (możesz też określić tekst " ", aby usunąć tekst tytułu okna).

Gdy polecenie to używane jest wewnątrz bloku PageEx: Ustawia podtytuł bieżącej strony.

Akceptowane są zmienne. Jeśli używane są zmienne, muszą być one zainicjowane w sekcji .onInit.

4.8.1.8 ChangeUI

dialog ui_file.exe

Zamienia okno dialogowe (IDD_LICENSE, IDD_DIR, IDD_SELCOM, IDD_INST, IDD_INSTFILES, IDD_UNINST lub IDD_VERIFY) oknem dialogowym o tym samym numerze ID zasobu w pliku ui_file.exe. Możesz również określić okno dialogowe jako 'all', jeśli chcesz zamienić wszystkie 7 okien dialogowych na raz z tego samego pliku UI. Przykłady wyglądu poszczególnych okien dialogowych znajdziesz w katalogu Contrib\UIs, jako podkatalog katalogu NSIS.

  • IDD_LICENSE musi zawierać IDC_EDIT1 (kontrolka RICHEDIT).
  • IDD_DIR musi zawierać IDC_DIR (kontrolka edycji tekstu), IDC_BROWSE (przycisk) oraz IDC_CHECK1 (pole wyboru).
  • IDD_SELCOM musi zawierać IDC_TREE1 (kontrolka SysTreeView32), oraz IDC_COMBO1 (pole kombinowane).
  • IDD_INST musi zawierać IDC_BACK (przycisk), IDC_CHILDRECT (kontrolka statyczna rozmiaru wszystkich innych okien dialogowych), IDC_VERSTR (static), IDOK (przycisk), oraz IDCANCEL (przycisk). Jeśli zostanie znaleziona kontrolka obrazka (kontrolka statyczna static ze stylem SS_BITMAP) w tym oknie dialogowym, zostanie ona użyta jako domyślna dla polecenia SetBrandingImage.
  • IDD_INSTFILES musi zawierać IDC_LIST1 (kontrolka SysListView32), IDC_PROGRESS (kontrolka msctls_progress32), oraz IDC_SHOWDETAILS (przycisk).
  • IDD_UNINST musi zawierać IDC_EDIT1 (pole edycji).
  • IDD_VERIFY musi zawierać IDC_STR (static).
ChangeUI all "${NSISDIR}\Contrib\UIs\sdbarker_tiny.exe"

4.8.1.9 CheckBitmap

bitmap.bmp

Określa bitmapę na obrazki, które używane są do zaznaczania wybranych opcji na drzewie wyboru komponentów do zainstalowania.

Bitmapa powinna mieć rozmiar 96x16 pikseli, nie więcej niż 8bpp (256 kolorów) i zawierać sześć obrazków 16x16 dla różnych stanów (w kolejności: maska zaznaczania, odznaczony, zaznaczony, zaszarzony, odznaczony & tylko do odczytu, zaznaczony & tylko do odczytu). Użyj magenty, jako koloru maskujacego (obszar ten będzie przezroczysty).

4.8.1.10 CompletedText

text

Zastępuje domyślny tekst ("Completed"), który jest wypisywany po zakończeniu instalacji, jeśli określono parametr. W przeciwnym razie używany jest domyślny.

Akceptowane są zmienne. Jeśli używane są zmienne, muszą być one zainicjowane przed wypisaniem komunikatu.

4.8.1.11 ComponentText

[text [subtext] [subtext2]]

Używany do zmiany domyślnego tekstu na stronie wyboru komponentów.

text: Tekst powyżej kontrolki, na prawo od ikonki instalatora.

subtext: Tekst naprzeciwko wyboru typu instalacji.

subtext2: Tekst na lewo od listy komponentów do zainstalowania i poniżej typu instalacji.

Domyślny tekst będzie użyty wtedy gdy ten ciąg znaków jest pusty ("").

Akceptowane są zmienne. Jeśli używane są zmienne, muszą być one zainicjowane przed utworzeniem strony wyboru komponentów.

4.8.1.12 CRCCheck

on|off|force

Określa czy instalator ma sprawdzać swoją sumę kontrolną CRC, przed kontynuowaniem instalacji. Pamiętaj, że jeśli użytkownik użyje przełącznika /NCRC w linii poleceń przy wykonywaniu programu, a ty nie określiłeś parametru 'force', suma kontrolna CRC nie będzie sprawdzana, a użytkownik będzie miał możliwość instalacji (potencjalnie) uszkodzonego instalatora.

4.8.1.13 DetailsButtonText

show details text

Zamienia domyślny tekst przycisku "Pokaż Szczegóły" (Show details), jeśli określono parametr (w przeciwnym razie użyty zostanie domyślny).

Akceptowane są zmienne. Jeśli używane są zmienne, muszą być one zainicjowane przed utworzeniem strony logu instalacji (instfiles).

4.8.1.14 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.

The default string will be used if a string is empty ("").

Akceptowane są zmienne. Jeśli używane są zmienne, muszą być one zainicjowane przed utworzeniem strony wyboru katalogu instalacji.

4.8.1.15 DirVar

user_var(dir input/output)

Określa zmienną, która przechowuje katalog instalacji. Zmienna ta powinna także zawierać domyślną wartość. Pozwala to na łatwe utworzenie dwóch różnych stron wyboru katalogu, które nie będą wymagały od ciebie przenoszenia wartości do i z poza katalogu $INSTDIR. Domyślną zmienną jest $INSTDIR. Może być ona użyta tylko w PageEx oraz dla katalogu oraz stron uninstConfirm.

Var INNY_KATALOG
PageEx katalog
  DirVar $INNY_KATALOG
PageExEnd

Section
  SetOutPath $INSTDIR
  File "plik.dat"
  SetOutPath $INNY_KATALOG
  File "inny plik.dat"
SectionEnd

4.8.1.16 DirVerify

auto|leave

If `DirVerify leave' is used, the Next button will not be disabled if the installation directory is not valid or there is not enough space. A flag that you can read in the leave function using GetInstDirError will be set instead.

PageEx directory
  DirVerify leave
  PageCallbacks "" "" dirLeave
PageExEnd

4.8.1.17 FileErrorText

File error text

Replaces the default text that comes up when a file cannot be written to. This string can contain a reference to $0, which is the filename ($0 is temporarily changed to this value). Example: "Can not write to file $\r$\n$0$\r$\ngood luck, bitch.".

Accepts variables. If variables are used, they must be initialized before File is used.

4.8.1.18 Icon

[path\]icon.ico

Sets the icon of the installer. Every icon in the icon file will be included in the installer. Note that if you use an uninstaller, each icon in the icon file must have the same size and color depth as its matching icon in the uninstaller icon file. The order of the icons in the icon file also matters. For example, if the installer icon file has three icons, first icon sized 32x32 pixels with 8bpp, second icon sized 16x16 pixels with 8bpp and third icon sized 8x8 with 8bpp; then the uninstaller icon file must have three icons with the same sizes and color depths, in the same order. Use UninstallIcon to set the uninstaller icon.

4.8.1.19 InstallButtonText

install button text

If parameter is specified, overrides the default install button text (of "Install") with the specified text.

Accepts variables. If variables are used, they must be initialized before the install button shows.

4.8.1.20 InstallColors

/windows | (foreground_color background_color)

Sets the colors to use for the install info screen (the default is 00FF00 000000. Use the form RRGGBB (in hexadecimal, as in HTML, only minus the leading '#', since # can be used for comments). Note that if "/windows" is specified as the only parameter, the default windows colors will be used.

4.8.1.21 InstallDir

definstdir

Sets the default installation directory. See the variables section for variables that can be used to make this string (especially $PROGRAMFILES). Note that the part of this string following the last \ will be used if the user selects 'browse', and may be appended back on to the string at install time (to disable this, end the directory with a \ (which will require the entire parameter to be enclosed with quotes). If this doesn't make any sense, play around with the browse button a bit.

4.8.1.22 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. If this attribute is present, it will override the InstallDir attribute if the registry key is valid, otherwise it will fall back to the InstallDir default. When querying the registry, this command will automatically remove any quotes. If the string ends in ".exe", it will automatically remove the filename component of the string (i.e. if the string is "C:\program files\poop\poop.exe", it will know to use "C:\program files\poop"). For more advanced install directory configuration, set $INSTDIR in .onInit.

Language strings and variables cannot be used with InstallDirRegKey.

InstallDirRegKey HKLM Software\NSIS ""
InstallDirRegKey HKLM Software\ACME\Thingy InstallLocation

4.8.1.23 InstProgressFlags

[flag [...]]

Valid values for flag are "smooth" (smooth the progress bar) or "colored" (color the progress bar with the colors set by InstallColors. Examples: "InstProgressFlags" (default old-school windows look), "InstProgressFlags smooth" (new smooth look), "InstProgressFlags smooth colored" (colored smooth look whee). Note: neither "smooth" or "colored" work with XPStyle on when the installer runs on Windows XP with a modern theme.

4.8.1.24 InstType

install_type_name | /NOCUSTOM | /CUSTOMSTRING=str | /COMPONENTSONLYONCUSTOM

Adds 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. If the name is prefixed with 'un.' it is an uninstaller install type. The name can contain variables 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, the component list will only be shown if the "Custom" install type is selected.

Accepts variables for type names. If variables are used, they must be initialized before the components page is created.

4.8.1.25 LicenseBkColor

color | /gray | /windows

Sets the background color of the license data. Color is specified using the form RRGGBB (in hexadecimal, as in HTML, only minus the leading '#', since # can be used for comments). Default is '/gray'. You can also use the Windows OS defined color by using '/windows'.

4.8.1.26 LicenseData

licdata.(txt|rtf)

Specifies a text file or a RTF file to use for the license that the user can read. Omit this to not have a license displayed. Note that the file must be in the evil DOS text format (\r\n, yeah!). To define a multilingual license data use LicenseLangString.

If you make your license file a RTF file it is recommended you edit it with WordPad and not MS Word. Using WordPad will result in a much smaller file.

Use LicenseLangString to show a different license for every language.

4.8.1.27 LicenseForceSelection

(checkbox [accept_text] | radiobuttons [accept_text] [decline_text] | off)

Specifies if the displayed license must be accept explicit or not. This can be done either by a checkbox or by radiobuttons. By default the "next button" is disabled and will only be enabled if the checkbox is enabled or the right radio button is selected. If off is specified the "next button" is enabled by default.

LicenseForceSelection checkbox
LicenseForceSelection checkbox "i accept"
LicenseForceSelection radiobuttons
LicenseForceSelection radiobuttons "i accept"
LicenseForceSelection radiobuttons "i accept" "i decline"
LicenseForceSelection radiobuttons "" "i decline"
LicenseForceSelection off

4.8.1.28 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.

The default string will be used if a string is empty ("").

Accepts variables. If variables are used, they must be initialized before the license page is created.

4.8.1.29 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 and Close). If parameters are omitted, the defaults are used.

Accepts variables. If variables are used, they must be initialized in .onInit.

4.8.1.30 Name

name [name_doubled_ampersands]

Sets the name of the installer. The name is usually simply the product name such as 'MyApp' or 'CrapSoft MyApp'. If you have one or more ampersands (&) in the name, set the second parameter to the same name, only with doubled ampersands. For example, if your product's name is "Foo & Bar", use:

 Name "Foo & Bar" "Foo && Bar"

If you have ampersands in the name and use a LangString for the name, you will have to create another one with doubled ampersands to use as the second parameter.

Accepts variables. If variables are used, they must be initialized in .onInit.

4.8.1.31 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.

4.8.1.32 RequestExecutionLevel

none|user|highest|admin

Specifies the requested execution level for Windows Vista. The value is embedded in the installer and uninstaller's XML manifest and tells Vista, and probably future versions of Windows, what privileges level the installer requires. user requests the a normal user's level with no administrative privileges. highest will request the highest execution level available for the current user and will cause Windows to prompt the user to verify privilege escalation. The prompt might request for the user's password. admin requests administrator level and will cause Windows to prompt the user as well. Specifying none, which is also the default, will keep the manifest empty and let Windows decide which execution level is required. Windows Vista automatically identifies NSIS installers and decides administrator privileges are required. Because of this, none and admin have virtually the same effect.

It's recommended, at least by Microsoft, that every application will be marked with the required execution level. Unmarked installers are subject to compatibility mode. Workarounds of this mode include automatically moving any shortcuts created in the user's start menu to all users' start menu. Installers that need not install anything into system folders or write to the local machine registry (HKLM) should specify user execution level.

More information about this topic can be found at MSDN. Keywords include "UAC", "requested execution level", "vista manifest" and "vista security".

4.8.1.33 SetFont

[/LANG=lang_id] font_face_name font_size

Sets the installer font. Please remember that the font you choose must be present on the user's machine as well. Don't use rare fonts that only you have.

Use the /LANG switch if you wish to set a different font for each language. For example:

 SetFont /LANG=${LANG_ENGLISH} "English Font" 9
 SetFont /LANG=${LANG_FRENCH} "French Font" 10

There are two LangStrings named ^Font and ^FontSize which contain the font and font size for every language.

4.8.1.34 ShowInstDetails

hide|show|nevershow

Sets whether or not the details of the install are shown. Can be 'hide' to hide the details by default, allowing the user to view them, or 'show' to show them by default, or 'nevershow', to prevent the user from ever seeing them. Note that sections can override this using SetDetailsView.

4.8.1.35 ShowUninstDetails

hide|show|nevershow

Sets whether or not the details of the uninstall are shown. Can be 'hide' to hide the details by default, allowing the user to view them, or 'show' to show them by default, or 'nevershow', to prevent the user from ever seeing them. Note that sections can override this using SetDetailsView.

4.8.1.36 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 this flag using SectionSetFlags), with no screen output from the installer itself (the script can still display whatever it wants, use MessageBox's /SD to specify a default for silent installers). Note that if this is set to 'normal' and the user runs the installer with /S (case sensitive) on the command line, it will behave as if SilentInstall 'silent' was used. Note: see also LogSet.

See section 4.12 for more information.

4.8.1.37 SilentUnInstall

normal|silent

Specifies whether or not the uninstaller should be silent. If it is 'silent' or 'silentlog', the uninstall section will run quietly, with no screen output from the uninstaller itself (the script can still display whatever it wants, use MessageBox's /SD to specify a default for silent installers). Note that if this is set to 'normal' and the user runs the uninstaller with /S on the command line, it will behave as if SilentUnInstall 'silent' was used. Note: see also LogSet.

See section 4.12 for more information.

4.8.1.38 SpaceTexts

[req 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.

Accepts variables. If variables are used, they must be initialized before the components page is created.

4.8.1.39 SubCaption

[page_number subcaption]

Overrides the subcaptions for each of the installer pages (0=": License Agreement",1=": Installation Options",2=": Installation Directory", 3=": Installing Files", 4=": Completed"). If you specify an empty string (""), the default will be used (you can however specify " " to achieve a blank string).

You can also set a subcaption (or override the default) using Caption inside a PageEx block.

Accepts variables. If variables are used, they must be initialized before the relevant page is created.

4.8.1.40 UninstallButtonText

text

Changes the text of the button that by default says "Uninstall" in the uninstaller. If no parameter is specified, the default text is used. See also WriteUninstaller (replaces UninstallEXEName).

Accepts variables. If variables are used, they must be initialized before the uninstall button shows.

4.8.1.41 UninstallCaption

caption

Sets what the titlebars of the uninstaller will display. By default, it is 'Name Uninstall', where Name is specified with the Name command. You can, however, override it with 'MyApp uninstaller' or whatever. If you specify an empty string (""), the default will be used (you can however specify " " to achieve a blank string).

Accepts variables. If variables are used, they must be initialized in un.onInit.

4.8.1.42 UninstallIcon

[path\]icon.ico

Sets the icon of the uninstaller. This icon file must have the exact same structure as the installer icon file. See Icon for more information about this limit.

4.8.1.43 UninstallSubCaption

page_number subcaption

Sets the default subcaptions for the uninstaller pages (0=": Confirmation",1=": Uninstalling Files",2=": Completed"). If you specify an empty string (""), the default will be used (you can however specify " " to achieve a blank string).

You can also set a subcaption (or override the default) using Caption inside a PageEx block.

Accepts variables. If variables are used, they must be initialized before the relevant page is created.

4.8.1.44 UninstallText

text [subtext]

Specifies the texts on the uninstaller confirm page.

text: Text above the controls

subtext: Text next to the uninstall location

Accepts variables. If variables are used, they must be initialized before the uninstaller confirm page is created.

4.8.1.45 WindowIcon

on|off

Sets whether or not the installer's icon is being displayed.

4.8.1.46 XPStyle

on|off

Sets whether or not an XP manifest will be added to the installer. An XP manifest makes the installer controls use the new XP style when running on Windows XP. This affects the uninstaller too.

4.8.2 Flagi Kompilatora

The following commands change 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).

4.8.2.1 AllowSkipFiles

on|off

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 (default) 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 (Cancel button) or retry opening the file for writing (Retry button). If on is used the user will have an option to skip the file (error flag will be set - see SetOverwrite).

4.8.2.2 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 any given time for file buffers. This command does not limit the compression buffers which could take another couple of MB, neither does it limit the compiler's other internal buffers, but those shouldn't normally top 1MB anyway. Specifying a very small number could decrease performance. Specifying a very large number could exhaust system resources and force the compiler to cancel the compilation process. The default value is 32MB.

4.8.2.3 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. Typically the SetCompress flag will affect the commands after it, and the last SetCompress command in the file also determines whether or not the install info section and uninstall data of the installer is compressed. If compressflag is 'auto', then files are compressed if the compressed size is smaller than the uncompressed size. If compressflag is set to 'force', then the compressed version is always used. If compressflag is 'off' then compression is not used (which can be faster).

Note that this option has no effect when solid compression is used.

4.8.2.4 SetCompressor

[/SOLID] [/FINAL] zlib|bzip2|lzma

This command sets the compression algorithm used to compress files/data in the installer. It can only be used outside of sections and functions and before any data is compressed. Different compression methods can not be used for different files in the same installer. It is recommended to use it on the very top of the script to avoid compilation errors.

Three compression methods are supported: ZLIB, BZIP2 and LZMA.

ZLIB (the default) uses the deflate algorithm, it is a quick and simple method. With the default compression level it uses about 300 KB of memory.

BZIP2 usually gives better compression ratios than ZLIB, but it is a bit slower and uses more memory. With the default compression level it uses about 4 MB of memory.

LZMA is a new compression method that gives very good compression ratios. The decompression speed is high (10-20 MB/s on a 2 GHz CPU), the compression speed is lower. The memory size that will be used for decompression is the dictionary size plus a few KBs, the default is 8 MB.

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. This results in greater compression ratios.

4.8.2.5 SetCompressorDictSize

dict_size_mb

Sets the dictionary size in megabytes (MB) used by the LZMA compressor (default is 8 MB).

4.8.2.6 SetDatablockOptimize

on|off

This command tells the compiler whether or not to do datablock optimizations. Datablock optimizations have the compiler check to see if any data being added to the data block is already in the data block, and if so, it is simply referenced as opposed to added (can save a little bit of size). It is highly recommended to leave this option on.

4.8.2.7 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 the default.

4.8.2.8 SetOverwrite

on|off|try|ifnewer|ifdiff|lastused

This command sets the overwrite flag which is used by the File command to determine whether or not the file should overwrite any existing files that are present. If overwriteflag is 'on', files are overwritten (this is the default). If overwriteflag is 'off', files that are already present are not overwritten. If overwriteflag is 'try', files are overwritten if possible (meaning that if the file is not able to be written to, it is skipped without any user interaction). If overwriteflag is 'ifnewer', then files are only overwritten if the existing file is older than the new file. If overwriteflag is 'ifdiff', then files are only overwritten if the existing file is older or newer than the new file. Note that when in 'ifnewer' or 'ifdiff' mode, the destination file's date is set, regardless of what SetDateSave is set to.

SetOverwrite off
File program.cfg # config file we don't want to overwrite
SetOverwrite on

4.8.2.9 SetPluginUnload

manual|alwaysoff

This command sets the unload plug-in flag which is by CallInstDLL and plug-in calls. Setting this to always off will behave as if you have added the /NOUNLOAD to every CallInstDLL and plug-in call. Setting this to manual will only not unload if you specifically use /NOUNLOAD.

4.8.3 Informacje o Wersji

4.8.3.1 VIAddVersionKey

 [/LANG=id_języka] nazwa_klucza wartość

Dodaje pole do zakładki Wersja we Właściwościach Pliku. Może to być pole zarówno systemowe jak i zdefiniowane przez użytkownika. Poniższe pola są zdefiniowane przez System:

  • ProductName
  • Comments
  • CompanyName
  • LegalCopyright
  • FileDescription
  • FileVersion
  • ProductVersion
  • InternalName
  • LegalTrademarks
  • OriginalFilename
  • PrivateBuild
  • SpecialBuild

Nazwy tych pól tłumaczone są na język systemowy, podczas gdy pola zdefiniowane przez użytkownika pozostają nieprzetłumaczone.

VIAddVersionKey /LANG=${LANG_ENGLISH} "ProductName" "Aplikacja Testowa"
VIAddVersionKey /LANG=${LANG_ENGLISH} "Comments" "Komentarz testowy"
VIAddVersionKey /LANG=${LANG_ENGLISH} "CompanyName" "Nazwa Firmy"
VIAddVersionKey /LANG=${LANG_ENGLISH} "LegalTrademarks" "Aplikacja testowa jest marką Nazwa Firmy"
VIAddVersionKey /LANG=${LANG_ENGLISH} "LegalCopyright" "© Nazwa Firmy"
VIAddVersionKey /LANG=${LANG_ENGLISH} "FileDescription" "Aplikacja Testowa"
VIAddVersionKey /LANG=${LANG_ENGLISH} "FileVersion" "1.2.3"

4.8.3.2 VIProductVersion

[version_string_X.X.X.X]

Dodaje Wersję Produktu na górze zakładki Wersja we Właściwościach Pliku.

VIProductVersion "1.2.3.4"

4.9 Instrukcje

4.9.1 Instrukcje Podstawowe

The instructions that NSIS uses for scripting are sort of a cross between PHP and assembly. There are no real high level language constructs, but the instructions themselves are (for the most part) high level, and you have handy string capability (i.e. you don't have to worry about concatenating strings, etc). You essentially have 25 registers (20 general purpose, 5 special purpose), and a stack.

4.9.1.1 Delete

[/REBOOTOK] file

Delete file (which can be a file or wildcard, but should be specified with a full path) from the target system. If /REBOOTOK is specified and the file cannot be deleted then the file is deleted when the system reboots -- if the file will be deleted on a reboot, the reboot flag will be set. The error flag is set if files are found and cannot be deleted. The error flag is not set from trying to delete a file that does not exist.

Delete $INSTDIR\somefile.dat

4.9.1.2 Exec

command

Execute the specified program and continue immediately. Note that the file specified must exist on the target system, not the compiling system. $OUTDIR is used for the working directory. The error flag is set if the process could not be launched. Note, if the command could have spaces, you should put it in quotes to delimit it from parameters. e.g.: Exec '"$INSTDIR\command.exe" parameters'. If you don't put it in quotes it will not work on Windows 9x with or without parameters.

Exec '"$INSTDIR\someprogram.exe"'
Exec '"$INSTDIR\someprogram.exe" some parameters'

4.9.1.3 ExecShell

action command [parameters] [SW_SHOWNORMAL | SW_SHOWMAXIMIZED | SW_SHOWMINIMIZED | SW_HIDE]

Execute the specified program using ShellExecute. Note that action is usually "open", "print", etc, but can be an empty string to use the default action. Parameters and the show type are optional. $OUTDIR is used for the working directory. The error flag is set if the process could not be launched.

ExecShell "open" "http://nsis.sf.net/"
ExecShell "open" "$INSTDIR\readme.txt"
ExecShell "print" "$INSTDIR\readme.txt"

4.9.1.4 ExecWait

command [user_var(exit code)]

Execute the specified program and wait for the executed process to quit. See Exec for more information. If no output variable is specified ExecWait sets the error flag if the program executed returns a nonzero error code, or if there is an error. If an output variable is specified, ExecWait sets the variable with the exit code (and only sets the error flag if an error occurs; if an error occurs the contents of the user variable are undefined). Note, if the command could have spaces, you should put it in quotes to delimit it from parameters. e.g.: ExecWait '"$INSTDIR\command.exe" parameters'. If you don't put it in quotes it will not work on Windows 9x with or without parameters.

ExecWait '"$INSTDIR\someprogram.exe"'
ExecWait '"$INSTDIR\someprogram.exe"' $0
DetailPrint "some program returned $0"

4.9.1.5 File

[/nonfatal] [/a] ([/r] [/x file|wildcard [...]] (file|wildcard) [...] | /oname=file.dat infile.dat)

Adds file(s) to be extracted to the current output path ($OUTDIR).

  • Note that the output file name is $OUTDIR\filename_portion_of_file.
  • If the /oname=X switch is used, the output name becomes $OUTDIR\X. When using the /oname= switch, only one file can be specified, and the file name can contain variables (or a fully qualified path, e.g. $SYSDIR\whatever.dll). If the output name contains spaces, quote the entire parameter, including /oname, as shown in the examples below.
  • Wildcards are supported.
  • If the /r switch is used, matching files and directories are recursively searched for in subdirectories. If just one path segment is specified (e.g. File /r something), the current directory will be recursively searched. If more than one segment is specified (e.g. File /r something\*.*), the last path segment will be used as the matching condition and the rest for the directory to search recursively. If a directory name matches, all of its contents is added recursively. Directory structure is preserved.
  • Use the /x switch to exclude files or directories.
  • If the /a switch is used, the attributes of the file(s) added will be preserved.
  • The File command sets the error flag if overwrite mode is set to 'try' and the file could not be overwritten, or if the overwrite mode is set to 'on' and the file could not be overwritten and the user selects ignore.
  • If the /nonfatal switch is used and no files are found, a warning will be issued instead of an error.
File something.exe
File /a something.exe
File *.exe
File /r *.dat
File /r data
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\*.*

Note: when using the /r switch, both matching 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. That means, the following directory structure:

<DIR> something
  File.dat
  another.dat
<DIR> dir
  something
  <DIR> dir2
    file2.dat
<DIR> another
  <DIR> something
    readme.txt

with the following File usage:

File /r something

will match the directory named something on the root directory, the file named something in the directory named dir and the directory named something in the directory named another. To match only the directory named something on the root directory, use the following:

File /r something\*.*

When adding \*.*, it will be used as the matching condition and something will be used as the directory to search. When only something is specified, the current directory will be recursively searched for every and directory named something and another\something will be matched.

4.9.1.6 Rename

[/REBOOTOK] source_file dest_file

Rename source_file to dest_file. You can use it to move a file from anywhere on the system to anywhere else and you can move a directory to somewhere else on the same drive. The destination file must not exist or the move will fail (unless you are using /REBOOTOK). If /REBOOTOK is specified, and the file cannot be moved (if, for example, the destination exists), then the file is moved when the system reboots. If the file will be moved on a reboot, the reboot flag will be set. The error flag is set if the file cannot be renamed (and /REBOOTOK is not used) or if the source file does not exist.

If no absolute path is specified the current folder will be used. The current folder is the folder set using the last SetOutPath instruction. If you have not used SetOutPath the current folder is $EXEDIR.

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

4.9.1.7 ReserveFile

[/nonfatal] [/r] [/x file|wildcard [...]] file [file...]

Reserves a file in the data block for later use. Files are added to the compressed data block in the order they appear in the script. Functions, however, are not necessarily called in the order they appear in the script. Therefore, if you add a file in a function called early but put the function at the end of the script, all of the files added earlier will have to be decompressed to get to the required file. This process can take a long time if there a lot of files. .onInit is one such function. It is called at the very beginning, before anything else appears. If you put it at the very end of the script, extract some files in it and have lots of files added before it, the installer might take a very long time to load. This is where this command comes useful, allowing you to speed up the loading process by including the file at the top of the data block instead of letting NSIS seek all the way down to the bottom of the compressed data block.

See File for more information about the parameters.

4.9.1.8 RMDir

[/r] [/REBOOTOK] directory_name

Remove the specified directory (fully qualified path with no wildcards). Without /r, the directory will only be removed if it is completely empty. If /r is specified, the directory will be removed recursively, so all directories and files in the specified directory will be removed. If /REBOOTOK is specified, any file or directory which could not have been removed during the process will be removed on reboot -- if any file or directory will be removed on a reboot, the reboot flag will be set. The error flag is set if any file or directory cannot be removed.

RMDir $INSTDIR
RMDir $INSTDIR\data
RMDir /r /REBOOTOK $INSTDIR
RMDir /REBOOTOK $INSTDIR\DLLs

Note that the current working directory can not be deleted. The current working directory is set by SetOutPath. For example, the following example will not delete the directory.

SetOutPath $TEMP\dir
RMDir $TEMP\dir

The next example will succeed in deleting the directory.

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

Warning: using RMDir /r $INSTDIR in the uninstaller is not safe. Though it is unlikely, the user might select to install to the Program Files folder and so this command will wipe out the entire Program Files folder, including other programs that has nothing to do with the uninstaller. The user can also put other files but the program's files and would expect them to get deleted with the program. Solutions are available for easily uninstalling only files which were installed by the installer.

4.9.1.9 SetOutPath

outpath

Ustawia wyjściową ścieżkę dostępu ($OUTDIR) i tworzy ją (rekursywnie, jeśli jest taka potrzeba), jeśli nie istnieje. Musi być pełną ścieżką dostępu, zazwyczaj jednak określana jest jako zmienna $INSTDIR (możesz określić zmienną $INSTDIR pojedynczym znakiem "-").

SetOutPath $INSTDIR
File program.exe

4.9.2 Instrukcje Plikowe, Rejestru, Plików INI

In all of the below registry instructions use an empty string (just two quotes with nothing between them - "") as the key name to specify the default key which is shown as (Default) in regedit.exe.

If a full path is not specified for any of the INI handling instructions, the Windows directory will be used.

4.9.2.1 DeleteINISec

ini_filename section_name

Deletes the entire section [section_name] from ini_filename. If the section could not be removed from the 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

4.9.2.2 DeleteINIStr

ini_filename section_name str_name

Deletes the string str_name from section [section_name] from ini_filename. If the string could not be removed from the ini file, the error flag is set. It does not set the error flag if the string could not be found.

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

4.9.2.3 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 (otherwise, the whole registry tree will be removed). Valid values for root_key are listed under WriteRegStr. The error flag is set if the key could not be removed from the registry (or if it didn't exist to begin with).

DeleteRegKey HKLM "Software\My Company\My Software"
DeleteRegKey /ifempty HKLM "Software\A key that might have subkeys"

4.9.2.4 DeleteRegValue

root_key subkey key_name

Deletes a registry value. Valid values for root_key are listed under WriteRegStr. The error flag is set if the value could not be removed from the registry (or if it didn't exist to begin with).

DeleteRegValue HKLM "Software\My Company\My Software" "some value"

4.9.2.5 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. Valid values for root_key are listed under WriteRegStr. Returns an empty string if there are no more keys, and returns an empty string and sets the error flag if there is an error.

StrCpy $0 0
loop:
  EnumRegKey $1 HKLM Software $0
  Pop $1 "" done
  IntOp $0 $0 + 1
  MessageBox MB_YESNO|MB_ICONQUESTION "$1$\n$\nMore?" IDYES loop
done:

4.9.2.6 EnumRegValue

user_var(output) root_key subkey index

Set user variable $x with the name of the 'index'th registry value in root_key\Subkey. Valid values for root_key are listed under WriteRegStr. Returns an empty string and sets the error flag if there are no more values or if there is an error.

StrCpy $0 0
loop:
  ClearErrors
  EnumRegValue $1 HKLM Software\Microsoft\Windows\CurrentVersion $0
  IfErrors done
  IntOp $0 $0 + 1
  ReadRegStr $2 HKLM Software\Microsoft\Windows\CurrentVersion $1
  MessageBox MB_YESNO|MB_ICONQUESTION "$1 = $2$\n$\nMore?" IDYES loop
done:

4.9.2.7 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". If there is an error, the variable is set to empty, and the error flag is set.

ExpandEnvStrings $0 "WINDIR=%WINDIR%$\nTEMP=%TEMP%"

4.9.2.8 FlushINI

ini_filename

Flushes the INI file's buffers. Windows 9x keeps all changes to the INI file in memory. This command causes the changes to be written to the disk immediately. Use it if you edit the INI manually, delete it, move it or copy it right after you change it with WriteINIStr, DeleteINISec or DeleteINStr.

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

4.9.2.9 ReadEnvStr

user_var(output) name

Reads from the environment string "name" and sets the value into the user variable $x. If there is an error reading the string, the user variable is set to empty, and the error flag is set.

ReadEnvStr $0 WINDIR
ReadEnvStr $1 TEMP

4.9.2.10 ReadINIStr

user_var(output) ini_filename section_name entry_name

Reads from entry_name in [section_name] of ini_filename and stores the value into user variable $x. The error flag will be set and $x will be assigned to an empty string if the entry is not found.

ReadINIStr $0 $INSTDIR\winamp.ini winamp outname

4.9.2.11 ReadRegDWORD

user_var(output) root_key sub_key name

Reads a 32 bit DWORD from the registry into the user variable $x. Valid values for root_key are listed under WriteRegStr. The error flag will be set and $x will be set to an empty string ("" which is 0) if the DWORD is not present. If the value is present, but is not a DWORD, it will be read as a string and the error flag will be set.

ReadRegDWORD $0 HKLM Software\NSIS VersionBuild

4.9.2.12 ReadRegStr

user_var(output) root_key sub_key name

Reads from the registry into the user variable $x. Valid values for root_key are listed under WriteRegStr. The error flag will be set and $x will be set to an empty string ("") if the string is not present. If the value is present, but is of type REG_DWORD, it will be read and converted to a string and the error flag will be set.

ReadRegStr $0 HKLM Software\NSIS ""
DetailPrint "NSIS is installed at: $0"

4.9.2.13 WriteINIStr

ini_filename section_name entry_name value

Writes entry_name=value into [section_name] of ini_filename. The error flag is set if the string could not be written to the ini file.

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

4.9.2.14 WriteRegBin

root_key subkey key_name valuedata

This command writes a block of binary data to the registry. Valid values for root_key are listed under WriteRegStr. Valuedata is in hexadecimal (e.g. DEADBEEF01223211151). The error flag is set if the binary data could not be written to the registry. If the registry key doesn't exist it will be created.

WriteRegBin HKLM "Software\My Company\My Software" "Binary Value" DEADBEEF01223211151

4.9.2.15 WriteRegDWORD

root_key subkey key_name value

This command writes a dword (32 bit integer) to the registry (a user variable can be specified). Valid values for root_key are listed under WriteRegStr. The error flag is set if the dword could not be written to the registry. If the registry key doesn't exist it will be created.

WriteRegDWORD HKLM "Software\My Company\My Software" "DWORD Value" 0xDEADBEEF

4.9.2.16 WriteRegStr

root_key subkey key_name value

Write a string to the registry. See WriteRegExpandStr for more details.

WriteRegStr HKLM "Software\My Company\My Software" "String Value" "dead beef"

4.9.2.17 WriteRegExpandStr

root_key subkey key_name value

Write a string to the registry. root_key must be one of:

  • HKCR or HKEY_CLASSES_ROOT
  • HKLM or HKEY_LOCAL_MACHINE
  • HKCU or HKEY_CURRENT_USER
  • HKU or HKEY_USERS
  • HKCC or HKEY_CURRENT_CONFIG
  • HKDD or HKEY_DYN_DATA
  • HKPD or HKEY_PERFORMANCE_DATA
  • SHCTX or SHELL_CONTEXT

If root_key is SHCTX or SHELL_CONTEXT, it will be replaced with HKLM if SetShellVarContext is set to all and with HKCU if SetShellVarContext is set to current.

The error flag is set if the string could not be written to the registry. The type of the string will be REG_SZ for WriteRegStr, or REG_EXPAND_STR for WriteRegExpandStr. If the registry key doesn't exist it will be created.

WriteRegExpandStr HKLM "Software\My Company\My Software" "Expand String Value" "%WINDIR%\notepad.exe"

4.9.3 Instrukcje Ogólnego Przeznaczenia

4.9.3.1 CallInstDLL

dllfile [/NOUNLOAD] function_name

Calls a function named function_name inside a NSIS extension DLL, a plug-in. See Contrib\ExDLL in the source code package for an example of how to make one. Extension DLLs can access the stack and variables. Use /NOUNLOAD to force the installer to leave the DLL loaded. Note: To automatically extract and call plug-in DLLs, use a plug-in command instead of CallInstDLL.

Push "a parameter"
Push "another parameter"
CallInstDLL $INSTDIR\somedll.dll somefunction

For easier plug-in handling, use the new plug-in call syntax.

4.9.3.2 CopyFiles

[/SILENT] [/FILESONLY] filespec_on_destsys destination_path [size_of_files_in_kb]

Copies files from the source to the destination on the installing system. Useful with $EXEDIR if you want to copy from installation media, or to copy from one place to another on the system. You might see a Windows status window of the copy operation if the operation takes a lot of time (to disable this, use /SILENT). The last parameter can be used to specify the size of the files that will be copied (in kilobytes), so that the installer can approximate the disk space requirements. On error, or if the user cancels the copy (only possible when /SILENT was omitted), the error flag is set. If /FILESONLY is specified, only files are copied.

Fully-qualified path names should always be used with this instruction. Using relative paths will have unpredictable results.

CreateDirectory $INSTDIR\backup
CopyFiles $INSTDIR\*.dat $INSTDIR\backup

4.9.3.3 CreateDirectory

path_to_create

Creates (recursively if necessary) the specified directory. The error flag is set if the directory couldn't be created.

You should always specify an absolute path.

CreateDirectory $INSTDIR\some\directory

4.9.3.4 CreateShortCut

link.lnk target.file [parameters [icon.file [icon_index_number [start_options [keyboard_shortcut [description]]]]]]

Creates a shortcut 'link.lnk' that links to 'target.file', with optional parameters 'parameters'. The icon used for the shortcut is 'icon.file,icon_index_number'; for default icon settings use empty strings for both icon.file and icon_index_number. start_options should be one of: SW_SHOWNORMAL, SW_SHOWMAXIMIZED, SW_SHOWMINIMIZED, or an empty string. keyboard_shortcut should be in the form of 'flag|c' where flag can be a combination (using |) of: ALT, CONTROL, EXT, or SHIFT. c is the character to use (a-z, A-Z, 0-9, F1-F24, etc). Note that no spaces are allowed in this string. A good example is "ALT|CONTROL|F8". $OUTDIR is used for the working directory. You can change it by using SetOutPath before creating the Shortcut. description should be the description of the shortcut, or comment as it is called under XP. The error flag is set if the shortcut cannot be created (i.e. either of the paths (link or target) does not exist, or some other error).

CreateDirectory "$SMPROGRAMS\My Company"
CreateShortCut "$SMPROGRAMS\My Company\My Program.lnk" "$INSTDIR\My Program.exe" \
  "some command line parameters" "$INSTDIR\My Program.exe" 2 SW_SHOWNORMAL \
  ALT|CTRL|SHIFT|F5 "a description"

4.9.3.5 GetDLLVersion

filename user_var(high dword output) user_var(low dword output)

Gets the version information from the DLL (or any other executable containing version information) in "filename". Sets the user output variables with the high and low dwords of version information on success; on failure the outputs are empty and the error flag is set. The following example reads the DLL version and copies a human readable version of it into $0:

GetDllVersion "$INSTDIR\MyDLL.dll" $R0 $R1
IntOp $R2 $R0 / 0x00010000
IntOp $R3 $R0 & 0x0000FFFF
IntOp $R4 $R1 / 0x00010000
IntOp $R5 $R1 & 0x0000FFFF
StrCpy $0 "$R2.$R3.$R4.$R5"

4.9.3.6 GetDLLVersionLocal

localfilename user_var(high dword output) user_var(low dword output)

This is similar to GetDLLVersion, only it acts on the system building the installer (it actually compiles into two StrCpy commands). Sets the two output variables with the DLL version information of the DLL on the build system.

4.9.3.7 GetFileTime

filename user_var(high dword output) user_var(low dword output)

Gets the last write time of "filename". Sets the user output variables with the high and low dwords of the timestamp on success; on failure the outputs are empty and the error flag is set.

4.9.3.8 GetFileTimeLocal

localfilename user_var(high dword output) user_var(low dword output)

This is similar to GetFileTime, only it acts on the system building the installer (it actually compiles into two StrCpy commands). Sets the two output variables with the file timestamp of the file on the build system.

4.9.3.9 GetFullPathName

[/SHORT] user_var(output) path_or_file

Assign to the user variable $x, the full path of the file specified. If the path portion of the parameter is not found, the error flag will be set and $x will be empty. If /SHORT is specified, the path is converted to the short filename form.

4.9.3.10 GetTempFileName

user_var(output) base_dir

Assign to the user variable $x, the name of a temporary file. The file will have been created, so you can then overwrite it with what you please. The name of the temporary file is guaranteed to be unique. If to want the temporary file to be created in another directory than the Windows temp directory, specify a base_dir. Delete the file when done with it.

GetTempFileName $0
File /oname=$0 something.dat
# do something with something.dat
Delete $0

4.9.3.11 SearchPath

user_var(output) filename

Assign to the user variable $x, the full path of the file named by the second parameter. The error flag will be set and $x will be empty if the file cannot be found. Uses SearchPath() to search the system paths for the file.

4.9.3.12 SetFileAttributes

filename attribute1|attribute2|...

Sets the file attributes of 'filename'. Valid attributes can be combined with | and are:

  • NORMAL or FILE_ATTRIBUTE_NORMAL (you can use 0 to abbreviate this)
  • ARCHIVE or FILE_ATTRIBUTE_ARCHIVE
  • HIDDEN or FILE_ATTRIBUTE_HIDDEN
  • OFFLINE or FILE_ATTRIBUTE_OFFLINE
  • READONLY or FILE_ATTRIBUTE_READONLY
  • SYSTEM or FILE_ATTRIBUTE_SYSTEM
  • TEMPORARY or FILE_ATTRIBUTE_TEMPORARY

The error flag will be set if the file's attributes cannot be set (i.e. the file doesn't exist, or you don't have the right permissions). You can only set attributes. It's not possible to unset them. If you want to remove an attribute use NORMAL. This way all attributes are erased. This command doesn't support wildcards.

4.9.3.13 RegDLL

dllfile [entrypoint_name]

Loads the specified DLL and calls DllRegisterServer (or entrypoint_name if specified). The error flag is set if an error occurs (i.e. it can't load the DLL, initialize OLE, find the entry point, or the function returned anything other than ERROR_SUCCESS (=0)).

Use SetOutPath to set the current directory for DLLs that depend on other DLLs that are now in the path or in the Windows directory. For example, if foo.dll depends on bar.dll which is located in $INSTDIR use:

 SetOutPath $INSTDIR
 RegDLL $INSTDIR\foo.dll

4.9.3.14 UnRegDLL

dllfile

Loads the specified DLL and calls DllUnregisterServer. The error flag is set if an error occurs (i.e. it can't load the DLL, initialize OLE, find the entry point, or the function returned anything other than ERROR_SUCCESS (=0)).

4.9.4 Instrukcje Kontroli Wykonania

4.9.4.1 Abort

user_message

Cancels the install, stops execution of script, and displays user_message in the status display. Note: you can use this from Callback functions to do special things. Page callbacks also uses Abort for special purposes.

Abort
Abort "can't install"

4.9.4.2 Call

function_name | :label_name | user_var(input)

Calls the function named function_name, the label named label_name, or a variable that specifies an address. An address is returned by GetCurrentAddress, GetFunctionAddress or GetLabelAddress. A call returns when it encounters a Return instruction. Sections and functions are automatically ended with a Return instruction. Uninstall functions cannot be called from installer functions and sections, and vice-versa.

Function func
  Call :label
  DetailPrint "#1: This will only appear 1 time."
label:
  DetailPrint "#2: This will appear before and after message #1."
  Call :.global_label
FunctionEnd

Section
  Call func
  Return

.global_label:
  DetailPrint "#3: The global label was called"
SectionEnd

4.9.4.3 ClearErrors

Clears the error flag.

ClearErrors
IfErrors 0 +2
  MessageBox MB_OK "this message box will never show"

4.9.4.4 GetCurrentAddress

user_var(output)

Gets the address of the current instruction (the GetCurrentAddress) and stores it in the output user variable. This user variable then can be passed to Call or Goto.

Function func
  DetailPrint "function"
  IntOp $0 $0 + 2
  Call $0
  DetailPrint "function end"
FunctionEnd

Section
  DetailPrint "section"
  DetailPrint "section"
  GetCurrentAddress $0
  Goto callFunc

  DetailPrint "back to section"
  Return

callFunc:
  Call func
  DetailPrint "section end"
SectionEnd

4.9.4.5 GetFunctionAddress

user_var(output) function_name

Gets the address of the function and stores it in the output user variable. This user variable then can be passed to Call or Goto. Note that if you Goto an address which is the output of GetFunctionAddress, your function will never be returned to (when the function you Goto'd to returns, you return instantly).

Function func
  DetailPrint "function"
FunctionEnd

Section
  GetFunctionAddress $0 func
  Call $0
SectionEnd

4.9.4.6 GetLabelAddress

user_var(output) label

Gets the address of the label and stores it in the output user variable. This user variable then can be passed to Call or Goto. Note that you may only call this with labels accessible from your function, but you can call it from anywhere (which is potentially dangerous). Note that if you Call the output of GetLabelAddress, code will be executed until it Return's (explicitly or implicitly at the end of a function), and then you will be returned to the statement after the Call.

label:
DetailPrint "label"
GetLabelAddress $0 label
IntOp $0 $0 + 4
Goto $0
DetailPrint "done"

4.9.4.7 Goto

label_to_jump_to | +offset| -offset| user_var(target)

If label is specified, goto the label 'label_to_jump_to:'.

If +offset or -offset is specified, jump is relative by offset instructions. Goto +1 goes to the next instruction, Goto -1 goes to the previous instruction, etc.

If a user variable is specified, jumps to absolute address (generally you will want to get this value from a function like GetLabelAddress). Compiler flag commands and SectionIn aren't instructions so jumping over them has no effect.

Goto label
Goto +2
Goto -2
Goto $0

4.9.4.8 IfAbort

label_to_goto_if_abort [label_to_goto_if_no_abort]

If abort is called it will "return" true. This can happen if the user chose abort on a file that failed to create (or overwrite) or if the user aborted by hand. This function can only be called from the leave function of the instfiles page.

Page instfiles "" "" instfilesLeave

Function instfilesLeave
  IfAbort 0 +2
    MessageBox MB_OK "user aborted"
FunctionEnd

4.9.4.9 IfErrors

jumpto_iferror [jumpto_ifnoerror]

Checks and clears the error flag, and if it is set, it will goto jumpto_iferror, otherwise it will goto jumpto_ifnoerror. The error flag is set by other instructions when a recoverable error (such as trying to delete a file that is in use) occurs.

ClearErrors
File file.dat
IfErrors 0 +2
  Call ErrorHandler

4.9.4.10 IfFileExists

file_to_check_for jump_if_present [jump_otherwise]

Checks for existence of file(s) file_to_check_for (which can be a wildcard, or a directory), and Gotos jump_if_present if the file exists, otherwise Gotos jump_otherwise. If you want to check to see if a file is a directory, use IfFileExists DIRECTORY\*.*

IfFileExists $WINDIR\notepad.exe 0 +2
  MessageBox MB_OK "notepad is installed"

4.9.4.11 IfRebootFlag

jump_if_set [jump_if_not_set]

Checks the reboot flag, and jumps to jump_if_set if the reboot flag is set, otherwise jumps to jump_if_not_set. The reboot flag can be set by Delete and Rename, or manually with SetRebootFlag.

IfRebootFlag 0 noreboot
  MessageBox MB_YESNO "A reboot is required to finish the installation. Do you wish to reboot now?" IDNO noreboot
    Reboot
noreboot:

4.9.4.12 IfSilent

jump_if_silent [jump_if_not]

Checks the silent flag, and jumps to jump_if_silent if the installer is silent, otherwise jumps to jump_if_not. The silent flag can be set by SilentInstall, SilentUninstall, SetSilent and by the user passing /S on the command line.

IfSilent +2
  ExecWait '"$INSTDIR\nonsilentprogram.exe"'

4.9.4.13 IntCmp

val1 val2 jump_if_equal [jump_if_val1_less] [jump_if_val1_more]

Compares two integers val1 and val2. If val1 and val2 are equal, Gotos jump_if_equal, otherwise if val1 < val2, Gotos jump_if_val1_less, otherwise if val1 > val2, Gotos jump_if_val1_more.

IntCmp $0 5 is5 lessthan5 morethan5
is5:
  DetailPrint "$$0 == 5"
  Goto done
lessthan5:
  DetailPrint "$$0 < 5"
  Goto done
morethan5:
  DetailPrint "$$0 > 5"
  Goto done
done:

4.9.4.14 IntCmpU

val1 val2 jump_if_equal [jump_if_val1_less] [jump_if_val1_more]

Compares two unsigned integers val1 and val2. If val1 and val2 are equal, Gotos jump_if_equal, otherwise if val1 < val2, Gotos jump_if_val1_less, otherwise if val1 > val2, Gotos jump_if_val1_more. Performs the comparison as unsigned integers.

4.9.4.15 MessageBox

mb_option_list messagebox_text [/SD return] [return_check jumpto] [return_check_2 jumpto_2]

Displays a MessageBox containing the text "messagebox_text". mb_option_list must be one or more of the following, delimited by |s (e.g. MB_YESNO|MB_ICONSTOP).

  • MB_OK - Display with an OK button
  • MB_OKCANCEL - Display with an OK and a cancel button
  • MB_ABORTRETRYIGNORE - Display with abort, retry, ignore buttons
  • MB_RETRYCANCEL - Display with retry and cancel buttons
  • MB_YESNO - Display with yes and no buttons
  • MB_YESNOCANCEL - Display with yes, no, cancel buttons
  • MB_ICONEXCLAMATION - Display with exclamation icon
  • MB_ICONINFORMATION - Display with information icon
  • MB_ICONQUESTION - Display with question mark icon
  • MB_ICONSTOP - Display with stop icon
  • MB_TOPMOST - Make messagebox topmost
  • MB_SETFOREGROUND - Set foreground
  • MB_RIGHT - Right align text
  • MB_RTLREADING - RTL reading order
  • MB_DEFBUTTON1 - Button 1 is default
  • MB_DEFBUTTON2 - Button 2 is default
  • MB_DEFBUTTON3 - Button 3 is default
  • MB_DEFBUTTON4 - Button 4 is default

Return_check can be 0 (or empty, or left off), or one of the following:

  • IDABORT - Abort button
  • IDCANCEL - Cancel button
  • IDIGNORE - Ignore button
  • IDNO - No button
  • IDOK - OK button
  • IDRETRY - Retry button
  • IDYES - Yes button

If the return value of the MessageBox is return_check, the installer will Goto jumpto.

Use the /SD parameter with one of the return_check values above to specify the option that will be used when the installer is silent. See section 4.12 for more information.

MessageBox MB_OK "simple message box"
MessageBox MB_YESNO "is it true?" IDYES true IDNO false
true:
  DetailPrint "it's true!"
  Goto next
false:
  DetailPrint "it's false"
next:
MessageBox MB_YESNO "is it true? (defaults to yes on silent installations)" /SD IDYES IDNO false2
  DetailPrint "it's true (or silent)!"
  Goto next2
false2:
  DetailPrint "it's false"
next2:

4.9.4.16 Return

Returns from a function or section.

Function func
  Pop $0 "return now" 0 +2
    Return
  # do stuff
FunctionEnd

Section
  Call func
  ;"Return" will return here
SectionEnd

4.9.4.17 Quit

Causes the installer to exit as soon as possible. After Quit is called, the installer will exit (no callback functions will get a chance to run).

4.9.4.18 SetErrors

Sets the error flag.

SetErrors
IfErrors 0 +2
  MessageBox MB_OK "this message box will always show"

4.9.4.19 StrCmp

str1 str2 jump_if_equal [jump_if_not_equal]

Compares (case insensitively) str1 to str2. If str1 and str2 are equal, Gotos jump_if_equal, otherwise Gotos jump_if_not_equal.

Pop $0 "a string" 0 +3
  DetailPrint '$$0 == "a string"'
  Goto +2
  DetailPrint '$$0 != "a string"'

4.9.4.20 StrCmpS

str1 str2 jump_if_equal [jump_if_not_equal]

Same as StrCmp, but case sensitive.

4.9.5 Instrukcje Plikowe

4.9.5.1 FileClose

handle

Zamyka uchwyt handle pliku, otwartego poleceniem FileOpen.

4.9.5.2 FileOpen

user_var(handle output) filename openmode

Otwiera plik o nazwie "filename", i ustawia wartość zmiennej wyjściowej uchwytem. Tryb openmode powinien być ustawiony na jeden z "r" (odczyt), "w" (zapis, cała zawartość pliku jest niszczona) lub "a" (dodane, w znaczeniu, że plik jest otwierany do odczytu i zapisu, zawartość jest zachowywana). We wszystkich trybach otwarcia, wskaźnik pliku umieszczany jest na poczatek pliku. Jeśli nie można otworzyć pliku, wyjściowy uchwyt ustawiany jest na pusty oraz ustawiana jest flaga błędu.

Jeśli nie określono ścieżki bezwzględnej użyty zostanie bieżący katalog. Bieżący katalog jest katalogiem ustawionym ostatnią instrukcją SetOutPath. Jeśli nie użyłeś wcześniej instrukcji SetOutPath, bieżący katalog jest katalogiem $EXEDIR.

FileOpen $0 $INSTDIR\plik.dat r
FileClose $0

4.9.5.3 FileRead

handle user_var(output) [maxlen]

Odczytuje łańcuch znaków z pliku otwartego poleceniem FileOpen. Łańcuch jest odczytywany aż do napotkania znaku nowej linii (lub znaku karetki), lub do czasu odczytania pustego bajtu (null) lub też do napotkania wartości maxlen (jeśli ją określono). Domyślnie, łańcuchy znaków ograniczone są do 1024 znaków (specjalny build z większą wartością NSIS_MAX_STRLEN można skompilować samodzielnie lub pobrać). Jeśli napotkano na koniec pliku i nie ma danych do odczytu, łańcuch wyjściowy jest pusty i ustawiana jest flaga błędu.

ClearErrors
FileOpen $0 $INSTDIR\plik.dat r
IfErrors done
FileRead $0 $1
DetailPrint $1
FileClose $0
done:

4.9.5.4 FileReadByte

handle user_var(output)

Odczytuje bajt z pliku otwartego poleceniem FileOpen. Bajt przechowywany jest na wyjściu jako liczba całkowita (integer) w zakresie (0-255). Jeśli napotkano na koniec pliku i nie ma danych do odczytu, łańcuch wyjściowy jest pusty i ustawiana jest flaga błędu.

ClearErrors
FileOpen $0 $INSTDIR\plik.dat r
IfErrors done
FileReadByte $0 $1
FileReadByte $0 $2
DetailPrint "$1 $2"
FileClose $0
done:

4.9.5.5 FileSeek

handle offset [mode] [user_var(new position)]

Przenosi wskaźnik pliku otwartego poleceniem FileOpen. Gdy pominięto parametr mode lub określony jest jako SET, pozycja pliku ustawiana jest na "offset", względem początku pliku. Gdy parametr mode określony jest jako CUR, pozycja pliku ustawiana jest na "offset", względem bieżącej pozycji pliku. Gdy parametr mode określony jest jako END, pozycja pliku ustawiana jest na "offset", względem końca pliku. Jeśli końcowy parametr nowej pozycji "new position" jest określony, nowa pozycja pliku przechowywana będzie w tej zmiennej.

ClearErrors
FileOpen $0 $INSTDIR\plik.dat r
IfErrors done
FileSeek $0 -5 END
FileRead $0 $1
DetailPrint $1
FileClose $0
done:

4.9.5.6 FileWrite

handle string

Zapisuje łańcuch znaków do pliku otwartego poleceniem FileOpen. Gdy pojawi się błąd zapisu, ustawiona zostanie flaga błędu.

ClearErrors
FileOpen $0 $INSTDIR\plik.dat w
IfErrors done
FileWrite $0 "jakiś tekst"
FileClose $0
done:

4.9.5.7 FileWriteByte

handle string

Zapisuje całkowitoliczbową (integer) interpretację łańcucha znaków 'string' do pliku otwartego poleceniem FileOpen. Oczywiście możesz wpisać bezpośrednio wartość całkowitą. Poniższy kod zapisuje znaki końca wiersza: "Powrotu Karetki / Nowej Lonii" - Enter do pliku.

FileWriteByte uchwyt_pliku "13"
FileWriteByte uchwyt_pliku "10"

Gdy wystąpi błąd podczas zapisu, ustawiona zostanie flaga błędu. Pamiętaj, że używane są niskie bajty liczby całkowitej, np. zapis 256 jest taki sam jak 0, etc.

4.9.5.8 FindClose

handle

Zamyka wyszukiwanie otwarte poleceniem FindFirst.

4.9.5.9 FindFirst

user_var(handle output) user_var(filename output) filespec

Wykonuje wyszukiwanie 'filespec', umieszczając pierwszy znaleziony plik w zmiennej użytkownika filename_output. Wstawia również uchwyt wyszukiwania do zmiennej użytkownika handle_output. Jeśli nie znaleziono żadnego pliku, obie zmienne wyjścia ustawiane są na puste i ustawiana jest flaga błędu. Najlepiej używać tego polecenia z poleceniami FindNext oraz FindClose. Pamiętaj, że wartość zmiennej filename output jest nazwą pliku bez ścieżki dostępu.

FindFirst $0 $1 $INSTDIR\*.txt
loop:
  Pop $1 "" done
  DetailPrint $1
  FindNext $0 $1
  Goto loop
done:

4.9.5.10 FindNext

handle user_var(filename_output)

Kontynuuje wyszukiwanie rozpoczęte poleceniem FindFirst. Uchwyt handle powinien być uchwytem zmiennej handle_output zwróconej przez polecenie FindFirst. Jeśli wyszukiwanie jest kompletne (nie ma już więcej plików spełniającyh kryteria wyszukiwania), zmienna filename_output ustawiana jest jako pusta i ustawiana jest flaga błędu. Pamiętaj, że wartość zmiennej filename_output jest nazwą pliku bez ścieżki dostępu.

4.9.6 Instrukcje Deinstalatora

4.9.6.1 WriteUninstaller

[Path\]exename.exe

Zapisuje instalatora do określonej nazwy pliku (i opcjonalnie ścieżki dostępu). Działa poprawnie tylko z sekcji instalacji lub funkcji i wymaga posiadania sekcji deinstalacji w skrypcie. Zobacz również Konfigurację Deinstalacji. Możesz wywołać to polecenie raz lub więcej razy, aby zapisać jedną lub więcej kopii deinstalatora.

WriteUninstaller $INSTDIR\uninstaller.exe

4.9.7 Inne Instrukcje

4.9.7.1 GetErrorLevel

user_var(error level output)

Zwraca ostatni poziom błędów, ustawiony przez polecenie SetErrorLevel lub -1 jeśli nie został użyty.

GetErrorLevel $0
IntOp $0 $0 + 1
SetErrorLevel $0

4.9.7.2 GetInstDirError

user_var(error output)

Użyj w funkcji wyjścia strony wyboru katalogu docelowego. Odczytuje ustawienie flagi, jeśli parametr leave funkcji DirVerify jest użyty. Możliwe wartości:

0: Bez błędów

1: Nieprawidłowy katalog instalacji

2: Niewystarczająca ilość miejsca na dysku

!include LogicLib.nsh
PageEx directory
  DirVerify leave
  PageCallbacks "" "" dirLeave
PageExEnd

Function dirLeave
  GetInstDirError $0
  ${Switch} $0
    ${Case} 0
      MessageBox MB_OK "prawidłowy katalog instalacji"
      ${Break}
    ${Case} 1
      MessageBox MB_OK "nieprawidłowy katalog instalacji!"
      Abort
      ${Break}
    ${Case} 2
      MessageBox MB_OK "brak miejsca na dysku!"
      Abort
      ${Break}
  ${EndSwitch}
FunctionEnd

4.9.7.3 InitPluginsDir

Inicjalizuje katalog wtyczek ($PLUGINSDIR), jeśli nie został jeszcze zainicjowany.

InitPluginsDir
File /oname=$PLUGINSDIR\image.bmp image.bmp

4.9.7.4 Nop

Nie robi nic.

4.9.7.5 SetErrorLevel

error_level

Ustawia poziom błędów instalatora lub deinstalatora na poziom błędów error_level. Aby dowiedzieć się więcej, czytaj o Poziomach Błędów.

IfRebootFlag 0 +2
  SetErrorLevel 4

4.9.7.6 SetShellVarContext

current|all

Ustawia zawartość zmiennej $SMPROGRAMS i innych folderów powłoki. Jeśli parametr ustawiony jest na bieżący 'current' (domyślnie), używane są foldery powłoki bieżącego użytkownika. Jeśli parametr ustawiony jest na wszyscy 'all', używany jest folder powłoki 'all users'. Folder all users może nie być obsługiwany na wszystkich systemach operacyjnych. Jeśli folderu all users nie znaleziono, użyty zostanie bieżący folder użytkownika. Proszę wziąść pod uwagę, że "zwykły użytkownik" nie posiada praw do zapisu w obszarze katalogu all users. Tylko administratorzy mają pełne prawa do zapisu w obszarze katalogu all users. Informację tę możesz sprawdzić używając wtyczki UserInfo. Dla przykładu zobacz Contrib\UserInfo\UserInfo.nsi.

Zauważ, że jeśli polecenie zostało użyte w kodzie instalatora, bedzie miało wpływ tylko na instalator, a jeśli zostało użyte w kodzie deinstalatora, bedzie miało wpływ tylko na deinstalatora. Aby można było oddziaływać na oba, musisz użyć tego polecenia w obu.

SetShellVarContext current
StrCpy $0 $DESKTOP
SetShellVarContext all
StrCpy $1 $DESKTOP
MessageBox MB_OK $0$\n$1

4.9.7.7 Sleep

sleeptime_in_ms

Wstrzymuje wykonywanie instalatora na okres czasu równy sleeptime_in_ms milisekund. Parametr sleeptime_in_ms może być zmienną, np. "$0" lub liczbą, np. "666".

DetailPrint "usypianie..."
Sleep 3000
DetailPrint "powrót do wykonywania"

4.9.8 Instrukcje do Manipulowania Łańcuchami Znaków

4.9.8.1 StrCpy

user_var(destination) str [maxlen] [start_offset]

Ustawia zmienną użytkownika $x przez str. Pamiętaj, że str może zawierać ine zmienne, lub ustawianą zmienną użytkownika (łączenie łańcuchów znaków tą metodą jest możliwe, itd.). Jeśli określony jest maxlen, łańcuch znaków bedzie miał maksymalny rozmiar znaków maxlen (jeśli maxlen jest ujemny, łańcuch znaków zostanie obcięty o abs(maxlen) znaków od końca). Jeśli określono początkową odległość start_offset, źródło jest oddalone o tę wartość (jeśli start_offset jest ujemna, zacznie od abs(start_offset) końca łańcucha znaków).

StrCpy $0 "a string" # = "a string"
StrCpy $0 "a string" 3 # = "a s"
StrCpy $0 "a string" -1 # = "a strin"
StrCpy $0 "a string" "" 2 # = "string"
StrCpy $0 "a string" "" -3 # = "ing"
StrCpy $0 "a string" 3 -4 # = "rin"

4.9.8.2 StrLen

user_var(length output) str

Ustawia zmienną użytkownika $x długością łańcucha znaków str.

StrLen $0 "123456" # = 6

4.9.9 Obsługa Stosu

4.9.9.1 Exch

[user_var | stack_index]

Jeśli nie określono żadnego parametru, wymienia dwa górne elementy stosu. Jeśli parametr jest określony i jest zmienną użytkownika, zmienia górny element stosu z parametrem. Jeśli parametr jest określony i jest dodatnią liczbą całkowitą, instrukcja Exch zamieni element będący na samej górze z elementem, który jest określony przez odległość od góry stosu w parametrze. Jeśli na stosie nie ma wystarczającej ilości elementów, aby dokończyć zamianę, wystąpi błąd krytyczny (aby pomóc ci odpluskwić kod :).

Push 1
Push 2
Exch
Pop $0 # = 1
Push 1
Push 2
Push 3
Exch 2
Pop $0 # = 1
StrCpy $0 1
Push 2
Exch $0 # = 2
Pop $1 # = 1

4.9.9.2 Pop

user_var(out)

Zdejmuje łańcuch znaków ze stosu i przypisuje do zmiennej użytkownika $x. Jeśli stos jest pusty, ustawiona zostanie flaga błędu.

Push 1
Pop $0 # = 1

4.9.9.3 Push

string

Odkłada łańcuch znaków na stos. Ten łańcuch znaków może być następnie zdjęty z niego (instrukcją Pop).

Push "łańcuch znaków"

4.9.10 Obsługa Typu Całkowitego Integer

4.9.10.1 IntFmt

user_var(output) format numberstring

Formatuje liczbę w "numberstring" używając formatu "format" i przypisuje wyjście do zmiennej użytkownka $x. Przykładowy sformatowany łańcuch znaków zawiera "%08X" "%u"

IntFmt $0 "0x%08X" 195948557
IntFmt $0 "%c" 0x41

4.9.10.2 IntOp

user_var(output) value1 OP [value2]

Łączy wartość value1 oraz wartość value2 (w oparciu o OP) w określoną zmienną użytkownika (user_var). OP zdefiniowane jest jako jedno z poniższych:

  • + Dodaje wartość value1 oraz wartość value2
  • - ZASTĘPUJE wartość value2 wartością value1
  • * MNOŻY wartość value1 oraz wartość value2
  • / DZIELI wartość value1 przez wartość value2
  • % MODULUSs wartości value1 przez wartość value2
  • | BINARNE LUB (OR) wartości value1 oraz wartość value2
  • & BINARNE ORAZ (AND) wartości value1 oraz wartość value2
  • ^ BINARNE XOR wartości value1 oraz wartość value2
  • >> PRZESUNIĘCIE BITOWE W PRAWO wartości value1 o wartość value2
  • << PRZESUNIĘCIE BITOWE W LEWO wartości value1 o value2
  • ~ NEGACJA BITOWA wartości value1 (np. 7 staje się 4294967288)
  • ! NEGACJA LOGICZNA wartości value1 (np. 7 staje się 0)
  • || LOGICZNE LUB (OR) wartości value1 oraz wartości value2
  • && LOGICZNE ORAZ (AND) wartości value1 oraz wartości value2
IntOp $0 1 + 1
IntOp $0 $0 + 1
IntOp $0 $0 << 2
IntOp $0 $0 ~
IntOp $0 $0 & 0xF

4.9.11 Instrukcje Ponownego Uruchamiania Komputera

4.9.11.1 Reboot

Uruchamia ponownie komputer. Bądź ostrożny z tą instrukcją. Jeśli się nie powiedzie wywoływana jest instrukcja .onRebootFailed. W każdym przypadku, instrukcja ta nigdy nie zwraca wyniku, tak jak Quit.

MessageBox MB_YESNO|MB_ICONQUESTION "Czy chcesz uruchomić ponownie komputer?" IDNO +2
  Reboot

4.9.11.2 SetRebootFlag

true|false

Ustawia flagę reboot ponownego uruchamiania komputera (true lub false). Wartość flagi może być odczytana dzięki instrukcji IfRebootFlag.

SetRebootFlag true
IfRebootFlag 0 +2
  MessageBox MB_OK "ten komunikat bedzie zawsze wyświetlany"

4.9.12 Instrukcje Logowania Postępu Instalacji

4.9.12.1 LogSet

on|off

Ustawia czy włączone będzie logowanie do pliku $INSTDIR\install.log. Zmienna $INSTDIR musi mieć wartość, zanim wywołasz tę funkcję; w przeciwnym razie nie będzie działać. Pamiętaj, że ustawienie budowania NSIS_CONFIG_LOG musi być ustawione (scons NSIS_CONFIG_LOG=yes) w czasie kompilacji (domyślnie nie jest), aby obsłużyć to polecenie. Zobacz Budowanie NSIS, aby dowiedzieć się więcej o rekompilacji NSIS.

4.9.12.2 LogText

text

Jeśli włączone jest logowanie instalacji, wstawia tekst "text" do pliku logu.

IfFileExists $WINDIR\notepad.exe 0 +2
  LogText "$$WINDIR\notepad.exe istnieje"

4.9.13 Zarządzanie Sekcjami

4.9.13.1 SectionSetFlags

section_index section_flags

Ustawia flagi dla sekcji. Flaga jest 32 bitową liczbą całkowitą. Pierwszy bit (najniższy) reprezentuje informację, czy sekcja jest aktualnie zaznaczona, drugi bit mówi o tym, czy sekcja jest grupą sekcji (zmieniaj tylko wtedy, gdy naprawdę wiesz co robisz), trzeci bit mówi o tym, czy sekcja jest grupą sekcji (znowu, nie modyfikuj), czwarty bit mówi o tym, czy sekcja jest wyświetlana pogrubioną czcionką lub nie, piaty bit mówi o tym, czy sekcja jest tylko do odczytu, szósty bit mówi o tym, czy grupa sekcji ma być automatycznie rozwinięta, siódmy bit ustawiany jest dla grupy sekcji, która jest częściowo zaznaczona, ósmy bit jest wykorzystywany wewnętrznie dla zmian częściowego zaznaczenia grupy sekcji oraz dziewiąty bit używany jest do odzwierciedlania zmian nazwy sekcji. Flaga błędu zostanie ustawiona jeśli wybrano sekcję z poza zakresu.

Każda flaga posiada nazwę, z prefiksem `SF_`:

!define SF_SELECTED   1
!define SF_SECGRP     2
!define SF_SECGRPEND  4
!define SF_BOLD       8
!define SF_RO         16
!define SF_EXPAND     32
!define SF_PSELECTED  64

Aby zobaczyć przykład użycia spójrz na skrypt one-section.nsi (../Examples/one-section.nsi).

Więcej przydatnych makr oraz definicji znajdziesz w Include\Sections.nsh.

Section test id_sekcji_test
SectionEnd

Function .onInit
  # ustawia sekcję 'test' jako zaznaczoną oraz tylko do odczytu
  IntOp $0 ${SF_SELECTED} | ${SF_RO}
  SectionSetFlags ${id_sekcji_test} $0
FunctionEnd

4.9.13.2 SectionGetFlags

section_index user_var(output)

Pobiera flagi sekcji. Popatrz powyżej na opis flag. Flaga błędu zostanie ustawiona, jeśli wybrano sekcję z poza zakresu.

Section test id_sekcji_test
SectionEnd

Function .onSelChange
  # utrzymaj zaznaczenie sekcji 'test'
  SectionGetFlags ${id_sekcji_test} $0
  IntOp $0 $0 | ${SF_SELECTED}
  SectionSetFlags ${id_sekcji_test} $0
FunctionEnd

4.9.13.3 SectionSetText

section_index section_text

Ustawia opis dla section_index sekcji. Jeśli tekst ustawiany jest na "", to sekcja zostanie ukryta. Flaga błędu zostanie ustawiona, jeśli wybrano sekcję z poza zakresu.

Section "" id_sekcji_test
SectionEnd

Function .onInit
  # zmień nazwę sekcji na $WINDIR
  SectionSetText ${id_sekcji_test} $WINDIR
FunctionEnd

4.9.13.4 SectionGetText

section_index user_var(output)

Przechowuje opis tekstowy section_index sekcji w output. Jeśli sekcja jest ukryta, przechowuje pusty łańcuch znaków. Flaga błędu zostanie ustawiona, jeśli wybrano sekcję z poza zakresu.

Section test id_sekcji_test
SectionEnd

Function .onInit
  # przypisuje zmienną $WINDIR do nazwy sekcji
  SectionGetText ${id_sekcji_test} $0
  StrCpy $0 "$0 - $WINDIR"
  SectionSetText ${id_sekcji_test} $0
FunctionEnd

4.9.13.5 SectionSetInstTypes

section_index inst_types

Ustawia typ instalacji sekcji określonej przez section_index domyślnie na włączony stan. Pamietaj, że indeks sekcji section_index zaczyna się od zera. Każdy bit inst_types jest flagą, która mówi o tym, czy sekcja jest w danym typie instalacji czy też nie. Na przykład, jeśli masz zdefiniowane 3 typy instalacji i chcesz by pierwsza z sekcji należała do typu instalacji 1 oraz 3, to polecenie powinno wygladać jak poniżej:

SectionSetInstTypes 0 5

ponieważ binarna wartość 5 równa się "00000101". Flaga błędu zostanie ustawiona, jeśli wybrano sekcję z poza zakresu.

Section test id_sekcji_test
SectionEnd

Function .onInit
  # wiąże sekcję 'test' z typem instalacji 3 oraz 4
  SectionSetInstTypes ${id_sekcji_test} 12
FunctionEnd

4.9.13.6 SectionGetInstTypes

section_index user_var(output)

Pobiera tablicę flag typów instalacji sekcji. Zobacz powyżej SectionSetInstTypes, aby dowiedzieć się w jaki sposób obsłużyć output. Flaga błędu zostanie ustawiona, jeśli wybrany indeks sekcji jest z poza zakresu.

Section test id_sekcji_test
SectionEnd

Function .onInit
  # wiąże sekcję 'test' z typem instalacji 5, na górze jej istniejacych powiązań
  SectionGetInstTypes ${id_sekcji_test} $0
  IntOp $0 $0 | 16
  SectionSetInstTypes ${id_sekcji_test} $0
FunctionEnd

4.9.13.7 SectionSetSize

section_index new_size

Ustawia rozmiar sekcji określonej przez indeks sekcji section_index. Pamiętaj, że indeksowanie rozpoczyna się od zera. Wartość dla rozmiaru musi być wpisana w kilobajtach i obsługuje tylko całe liczby.

Section test id_sekcji_test
SectionEnd

Function .onInit
  # ustawia wymagany rozmiar sekcji 'test' na 100 bajtów
  SectionSetSize ${id_sekcji_test} 100
FunctionEnd

4.9.13.8 SectionGetSize

section_index user_var

Pobiera rozmiar sekcji określonej przez indeks sekcji section_index i przechowuje go w podanej wartości Zmiennej Użytkownika. Pamiętaj, że indeksowanie rozpoczyna się od zera.

Section test id_sekcji_test
SectionEnd

Function .onInit
  # zwiększa wymagany rozmiar sekcji 'test' o 100 bajtów
  SectionGetSize ${id_sekcji_test} $0
  IntOp $0 $0 + 100
  SectionSetSize ${id_sekcji_test} $0
FunctionEnd

4.9.13.9 SetCurInstType

inst_type_idx

Ustawia aktualny typ instalacji InstType. Indeks typu instalacji inst_type_idx powinien zawierać się pomiędzy 0 a 31. Flaga błędu nie jest ustawiana, jeśli użyje się typ instalacji InstType z poza zakresu.

4.9.13.10 GetCurInstType

user_var

Pobiera aktualny typ instalacji InstType i przechowuje go w zmiennej użytkownika user_var. Jeśli wybrany jest pierwszy typ instalacji, do zmiennej user_var zostanie przypisana wartość 0. Jeśli wybrany zostanie drugi typ instalacji, do zmiennej user_var zostanie przypisana wartość 1 i tak dalej. Wartość ${NSIS_MAX_INST_TYPES} (domyślnie 32) oznacza, że wybrany został własny typ instalacji.

4.9.13.11 InstTypeSetText

inst_type_idx text

Ustawia Tekst text określonego typu instalacji InstType. Jeśli tekst jest pusty, typ instalacji zostaje usunięty. Używając poprzedniego nieużywanego numeru indeksu typu instalacji inst_type_idx, możesz stworzyć nowy typ instalacji. Aby dodać/usunąć Sekcje do tego nowego typu instalacji InstType zobacz SectionSetInstTypes. W przeciwieństwie do SectionIn indeks rozpoczyna się od zera, co oznacza, że indeksem pierwszego typu instalacji jest 0.

InstType a
InstType b

Function .onInit
  # ustaw nazwę pierwszego typu instalacji na $WINDIR
  InstTypeSetText 0 $WINDIR
  # ustaw nazwę drugiego typu instalacji na $TEMP
  InstTypeSetText 1 $TEMP
FunctionEnd

4.9.13.12 InstTypeGetText

inst_type_idx user_var

Pobiera Tekst Text określonego typu instalacji InstType.

InstType a
InstType b

Function .onInit
  InstTypeGetText 0 $0
  DetailPrint $0 # wydrukuje 'a'
  InstTypeGetText 1 $0
  DetailPrint $0 # wydrukuje 'b'
FunctionEnd

4.9.14 Instrukcje Interfejsu Użytkownika

4.9.14.1 BringToFront

Ustawia okno instalatora jako widoczne oraz na wierzchu listy okien. Jeśli aplikacja została uruchomiona w taki sposób, że wyświetlana jest na wierzchu instalatora, BringToFront przywróci okno instalatora z powrotem.

Najnowsze wersje Windows ograniczają ustawienia okien pierwszoplanowych. Jeśli użytkownik pracuje z inną aplikacją podczas instalowania, może być powiadomiony przy użyciu innej metody.

4.9.14.2 CreateFont

user_var(handle output) face_name [height] [weight] [/ITALIC] [/UNDERLINE] [/STRIKE]

Tworzy czcionkę i przypisuje jej uchwyt do zmiennej user_var. Więcej informacji o różnych parametrach znajdziesz na stronach MSDN, o funkcji Win32 API - CreateFont().

Możesz pobrać bieżącą czionkę używaną przez NSIS poprzez użycie ^Font oraz ^FontSize LangString.

!include WinMessages.nsh
GetDlgItem $0 $HWNDPARENT 1
CreateFont $1 "Times New Roman" "7" "700" /UNDERLINE
SendMessage $0 ${WM_SETFONT} $1 1

4.9.14.3 DetailPrint

user_message

Dodaje łańcuch znaków "user_message" do widoku szczegółów instalatora.

DetailPrint "ten komunikat zostanie wyświetlony w oknie instalacji"

4.9.14.4 EnableWindow

hwnd (1|0)

Włącza lub wyłącza wejście myszy lub klawiatury, dla określonego okna lub kontrolki. Możliwymi stanami są 0 (wyłączone) lub 1 (włączone).

GetDlgItem $0 $HWNDPARENT 1
EnableWindow $0 0
Sleep 1000
EnableWindow $0 1

4.9.14.5 FindWindow

user_var(hwnd output) windowclass [windowtitle] [windowparent] [childafter]

Wyszukuje okno. Zachowuje się tak, jak funkcja win32 FindWindowEx(). Wyszukuje przez klasę okna windowclass (oraz/lub tytuł okna windowtitle, jeśli jest określony). Jeśli określone są windowparent lub childafter, wyszukiwanie zostanie odpowiednio ograniczone. Jeśli windowclass lub windowtitle są określone jako "", nie bedą użyte w wyszukiwaniu. Jeśli nie znaleziono okna, zmienna użytkownika przyjmie wartość 0. Aby zrealizować zachowanie FindWindow w starym stylu, użyj FindWindow z SendMessage.

FindWindow $0 "#32770" "" $HWNDPARENT
FindWindow $0 "moja klasa okna" "mój tytuł okna"

4.9.14.6 GetDlgItem

user_var(output) dialog item_id

Pobiera uchwyt kontrolki identyfikowanej przez item_id w określonym oknie dialogowym dialog. Jeśli chcesz pobrać uchwyt kontrolki w wewnętrznym oknie dialogowym, wpierw użyj FindWindow user_var(output) "#32770" "" $HWNDPARENT, aby pobrać uchwyt wewnętrznego okna dialogowego.

GetDlgItem $0 $HWNDPARENT 1 # dalej/przycisk instaluj

4.9.14.7 HideWindow

Ukrywa okno instalatora.

4.9.14.8 IsWindow

HWND jump_if_window [jump_if_not_window]

Jeśli HWND jest oknem, użyj polecenia Goto jump_if_window, w przeciwnym przypadku, polecenie Goto jump_if_not_window (jeśli określone).

GetDlgItem $0 $HWNDPARENT 1
IsWindow $0 0 +3
  MessageBox MB_OK "znaleziono okno"
  Goto +2
  MessageBox MB_OK "brak okna"

4.9.14.9 LockWindow

on|off

LockWindow on uniemożliwia głównemu oknu przerysowywania siebie przy zmianach. Gdy użyjesz LockWindow off, wszystkie kontrolki, które nie zostały przerysowane od czasu użycia LockWindow on zostaną przerysowane. Sprawia to, że migotanie stron jest przyjemniejsze dla oka, ponieważ teraz miga cała grupa kontrolek w tym samym czasie, a nie jednej. Indywidualne migotanie kontrolki jest bardziej widoczne na starszych komputerach.

4.9.14.10 SendMessage

HWND msg wparam lparam [user_var(return value)] [/TIMEOUT=time_in_ms]

Wysyła komunikat do HWND. Jeśli określona jest zmienna użytkownika $x, jako ostatni parametr (lub przedostatni, jeśli użyjesz przełącznika /TIMEOUT), zwracana wartość SendMessage przechowywana będzie w niej. Pamiętaj, że określając 'msg' musisz użyć wartości całkowitej komunikatu. Jeśli chcesz wysłać łańcuch znaków użyj "STR:łańcuch znaków" jako wParam lub lParam, gdy jest taka potrzeba.

  • WM_CLOSE 16
  • WM_COMMAND 273
  • WM_USER 1024

Dołącz plik WinMessages.nsh do skryptu, by mieć zdefiniowane wszystkie komunikaty Windows we własnym skrypcie.

Aby wysłać łańcuch znaków, umieść STR: przed parametrem, na przykład: "STR:jakiś łańcuch znaków".

Użyj przełącznika /TIMEOUT=time_in_ms aby określić czas time-out, w milisekundach.

!include WinMessages.nsh
FindWindow $0 "Winamp v1.x"
SendMessage $0 ${WM_CLOSE} 0 0

4.9.14.11 SetAutoClose

true|false

Nadpisuje domyślną flagę automatycznego zamykania okna (określoną w instalatorze przez polecenie AutoCloseWindow, oraz z parametrem false dla deinstalatora). Ustaw parametr 'true', aby okno instalacji zniknęło natychmiast po zakończeniu instalacji, lub 'false', aby uczynić to ręcznie.

4.9.14.12 SetBrandingImage

[/IMGID=item_id_in_dialog] [/RESIZETOFIT] path_to_bitmap_file.bmp

Ustawia bieżący plik bitmapy jako obrazek firmowy. Jeśli nie określono IMGID, użyta zostanie pierwsza znaleziona kontrolka obrazka lub kontrolka obrazka utworzona przez AddBrandingImage. Pamiętaj, że bitmapa musi znajdować się na komputerze użytkownika. Użyj najpierw polecenia File, by ją tam umieścić. Jeśli określony jest przełącznik /RESIZETOFIT obrazek bedzieautomatycznie dopasowywany (nędznie) do rozmiaru kontrolki obrazka. Jeśli użyłeś polecenia AddBrandingImage możesz pobrać ten rozmiar, poprzez skompilowanie skryptu i wyszukanie tej informacji w wyjściu, przy poleceniu AddBrandingImage. SetBrandingImage nie bedzie działać, jeśli zostanie wywołane z funkcji .onInit!

4.9.14.13 SetDetailsView

show|hide

Wyświetla bądź ukrywa szczegóły, w zależności od użytego parametru. Nadpisuje domyślny widok szczegółów, który jest ustawiany przez ShowInstDetails.

4.9.14.14 SetDetailsPrint

none|listonly|textonly|both|lastused

Ustawia tryb, w którym polecenia wypisują swój status. Przy parametrze None szczegóły poleceń nie są wypisywane, przy parametrze listonly tekst statusu dodawany jest na listę elementów, przy parametrze textonly tekst statusu wydrukowywany jest tylko w pasku statusu, zaś parametr both aktywuje oba powyższe tryby (domyślnie). Do wyodrębniania wielu małych plików zaleca się aktywowanie trybu textonly (zwłaszcza w systemach win9x, z włączonym płynnym przewijaniem).

SetDetailsPrint none
File "tajny plik.dat"
SetDetailsPrint both

4.9.14.15 SetCtlColors

hwnd [/BRANDING] [text_color] [transparent|bg_color]

Ustawia kolor tła i kolor tekstu dla statycznej kontrolki, kontrolki edycji, przycisku lub okna dialogowego. text_color oraz bg_color nie akceptują zmiennych. Użyj instrukcji GetDlgItem, aby pobrać uchwyt (HWND) kontrolki. Aby kontrolka uzyskała właściwości przezroczystości, użyj wpisu "transparent", jako wartość koloru tła. Możesz również określić przełącznik /BRANDING z lub bez koloru tekstu i kolorem tła, aby uczynić kontrolke całkowicie szarą (lub użyć innego koloru, jaki wybierzesz). Własność ta używana jest dla tekstu branding w MUI.

FindWindow $0 "#32770" "" $HWNDPARENT
GetDlgItem $0 $0 1006
SetCtlColors $0 0xFF0000 0x00FF00

Uwaga: ustawienie koloru tła pół wyboru na "transparent" może nie działać poprawnie, gdy masz włączoną opcję XPStyle. Tło może być wtedy całkowicie czarne, zamiast przezroczystego, jeśli używasz styli systemu Windows.

4.9.14.16 SetSilent

silent | normal

Ustawia tryb wykonywania instalatora - cichy lub normalny. Więcej informacji o cichych instalatorach znajdziesz w SilentInstall. Instrukcja ta może być użyta tylko i wyłącznie w funkcji .onInit.

4.9.14.17 ShowWindow

hwnd show_state

Ustawia widoczność okna. Możliwe stany show_states są takie same jak w funkcji Windows ShowWindow. Stałe SW_* zdefiniowane są w pliku nagłówkowym Include\WinMessages.nsh.

!include WinMessages.nsh
GetDlgItem $0 $HWNDPARENT 1
ShowWindow $0 ${SW_HIDE}
Sleep 1000
ShowWindow $0 ${SW_SHOW}

4.9.15 Instrukcje Interfejsu Wielojęzykowego

4.9.15.1 LoadLanguageFile

plik_językowy.nlf

Wczytuje plik językowy dla struktury tablicy języka. Wszystkie pliki językowe, które rozprowadzane są z NSIS znajdują się w pliku Contrib\Language Files

Po wstawieniu pliku językowego ${LANG_langfile} zostanie zdefiniowany jako numer id języka (na przykład, ${LANG_ENGLISH} zostanie zdefiniowany jako 1033). Używaj tej instrukcji razem z instrukcjami LangString, LicenseLangString, LangDLL oraz VIAddVersionKey.

4.9.15.2 LangString

nazwa id_języka łańcuch_znaków

Definiuje wielojęzykowy łańcuch znaków. Oznacza to, że jego wartości mogą być różne (lub nie, to zależy od ciebie) dla każdego języka. Pozwala na łatwe tworzenie wielojęzykowych instalatorów, bez potrzeby dodawania wielu przełączników do skryptu.

Każdy łańcuch znaków języka posiada unikalną nazwę identyfikujacą go oraz wartość dla każdego z języków używanych przez instalatora. Mogą one być używane w dowolnym łańcuchu znaków w skrypcie, podczas wykonania. Wszystko co musisz zrobić, by móc użyć łańcucha znaków języka, to dodać do tego łańcucha znaków zmienną $(LangString_nazwa), tam gdzie chcesz wstawić LangString.

Uwagi:

  • W przeciwieństwie do definicji, które używają nawiasów klamrowych - {}, łańcuchy znaków języka używają nawiasów otwartych - ().
  • Jeśli zmienisz język w funkcji .onInit, pamietaj, że łańcuchy znaków języka w funkcji .onInit wciąż będą używać języka wykrytego w oparciu o domyślny język systemu Windows, ponieważ język inicjalizowany jest po wykonaniu funkcji .onInit.
  • Zawsze ustawiaj łańcuchy znaków języka dla każdego języka w swoim skrypcie.
  • Jeśli ustawisz numer ID języka na 0 użyty zostanie ostatnio używany język LangString lub LoadLanguageFile.

Przykład użycia:

 LangString komunikat ${LANG_ENGLISH} "Angielski komunikat"
 LangString komunikat ${LANG_FRENCH} "Francuski komunikat"
 LangString komunikat ${LANG_KOREAN} "Koreański komunikat"
 LangString komunikat ${LANG_POLISH} "Polski komunikat"
 MessageBox MB_OK "Przetłumaczony komunikat: $(komunikat)"

4.9.15.3 LicenseLangString

nazwa id_języka ścieżka_do_pliku_z_licencją

Spełnia taką samą funkcję co instrukcja LangString, ale wczytuje łańcuchy znaków z pliku tekstowego/RTF oraz definiuje specjalny LangString, który może być użyty tylko przez instrukcję LicenseData.

LicenseLangString licencja ${LANG_ENGLISH} license-english.txt
LicenseLangString licencja ${LANG_FRENCH} license-french.txt
LicenseLangString licencja ${LANG_GERMAN} license-german.txt
LicenseLangString licencja ${LANG_POLISH} polska_licencja.txt
LicenseData $(licencja)

4.10 Interfejs Wielojęzykowy

Poczynając od wersji 2 NSIS w pełni obsługuje instalatory wielojęzykowe. Interfejs jednego instalatora może korzystać z wielu języków.

Użyj polecenia LoadLanguageFile dla każdego języka, aby załadować teksty domyślnego interfejsu oraz właściwości języka.

Teksty interfejsu domyślnego mogą być łatwo zmienione poprzez użycie instrukcji takich jak ComponentText itd.

Możesz również użyć zawartości standardowych łańcuchów znaków języka we własnych (na przykład, $(^Name) zawiera nazwę instalatora, nadaną poprzez użycie polecenia Name). Nazwy wszystkich standardowych łańcuchów znaków języka są wylistowane jako komentarz tuż powyżej łańcuchów znaków w plikach językowych. Pliki językowe znajduja się w katalogu "Contrib\Language Files".

Aby utworzyć własny łańcuch znaków języka, użyj polecenia LangString.

Przykład instalatora wykorzystującego interfejs z wieloma językami znajdziesz w pliku "languages.nsi" w katalogu z przykładami.

4.10.1 Wybór Języka

Gdy instalator uruchamia się, wykonuje poniższe kroki, aby wybrać interfejs językowy:

  1. Pobranie domyślnego języka Windows
  2. Znalezienie idealnego dopasowania dla języka
  3. Jeśli nie znaleziono idealnego dopasowania, znajduje pierwszy pasujący język
  4. Jesli nie znaleziono dopasowania, używa pierwszego języka zdefiniowanego w skrypcie (upewnij się, że twój pierwszy język jest powszechny, jak angielski (English))
  5. Jeśli zmienna języka $LANGUAGE zmieniła swoją wartość w funkcji .onInit, NSIS rozpatruje ponownie kroki od 2 do 4.

4.10.2 Wtyczka LangDLL

Wtyczka LangDLL umożliwia użytkownikowi wybranie języka instalatora. Wystarczy odłożyć na stos id języka (${LANG_langfile}) oraz jego nazwę dla każdego języka twojego instalatora, następnie odłożyć liczbę tych języków, tekst w nagłówku oraz tekst, który mówi użytkownikowi, aby wybrał język, potem wywołać funkcję wtyczki LangDialog, a w końcu pobrać zwróconą wartość do zmiennej $LANGUAGE. Jeśli użytkownik kliknie na przycisk anuluj, zwróconą wartością będzie "cancel".

Przykład użycia znajdziesz w pliku "languages.nsi", który znajduje się w katalogu z przykładami.

4.10.3 Języki RTL

Języki RTL są językami, które zapisywane są z prawej do lewej (np. Arabski i Hebrajski). NSIS w pełni wspiera języki RTL. W pliku językowym jest miejsce, w którym określamy czy plik jest językiem RTL czy też nie. Aby dowiedzieć sie tego podczas wykonania, sprawdź wartość zmiennej $(^RTL) łańcucha znaków języka. Wartość ta będzie równa 1, jeśli język jest typu RTL, w przeciwnym razie równy jest 0. Może to być przydatne, gdy używa się wtyczek, które tworzą okna dialogowe, mają one także ustawienia RTL (zazwyczaj).


4.11 Pliki DLL Wtyczek

Możliwości języka skryptowego NSIS mogą być rozszerzone o funkcjonalność, którą dostarczaja pliki bibliotek DLL. Prawdopodobnie najlepszym znanym przykładem wykorzystania tych własności jest wtyczka InstallOptions.dll rozprowadzana z każdą dystrybucją NSIS.

Gdy kompilator NSIS startuje, skanuje katalog wtyczek w poszukiwaniu bibliotek DLL i tworzy listę znalezionych tam wtyczek oraz funkcji, które one eksportują. Podczas kompilacji, jeśli sekwencja taka jak fred::flintstone jest wyliczona gdzie kompilator spodziewa się znaleźć słowa kluczowego języka, kompilator pzeszukuje tę liste. Jeśli lista określa, że fred.dll eksportuje funkcję flintstone, NSIS dołączy (wkompresuje) plik fred.dll do utworzonego pliku binarnego instalatora.

Podczas wykonania polecenia wtyczki, NSIS rozpakuje odpowiednią bibliotekę DLL do katalogu tymczasowego ($PLUGINSDIR), odłoży wszystkie wymagane argumenty (w kolejności z prawej do lewej), a następnie wykona funkcję DLL. Jeśli opcja /NOUNLOAD jest określona biblioteka DLL nie zostanie wyładowana z pamięci dopóki instalator nie zakończy pracy lub zostanie ponownie użyta ta bilioteka DLL bez opcji /NOUNLOAD. Proszę zauważyć, że ostatnie wywołanie z wtyczki nie może mieć ustawionej flagi /NOUNLOAD, bo w tym wypadku wtyczka nie zostanie usunięta z katalogu tymczasowego $PLUGINSDIR, a co za tym idzie, na dysku użytkownika pozostaną zbędne pliki.

4.11.1 Używanie Poleceń Wtyczek

Wywołanie wtyczki wygląda następujaco:

InstallOptions::dialog "lokalizacja_pliku_ini.ini"

Wszystkie parametry odkładane sa na stos (w takim przypadku, funkcja wtyczki wymaga tylko jednego parametru). Niektóre polecenia wtyczki mogą nie wymagać żadnego parametru na stosie, inne mogą wymagać ich więcej. Aby użyć polecenia wtyczki będziesz musiał przeczytać dokumentację określonej wtyczki, by dowiedzieć się jakich parametrów funkcja wymaga.

4.11.2 Wyłączanie Wyładowywania Wtyczek

Jeśli nie chcesz wyładowywać biblioteki DLL po wywołaniu z niej funkcji, użyj /NOUNLOAD jako pierwszego parametru. Na przykład:

dll::function /NOUNLOAD "parametr"

Możesz również użyć polecenia SetPluginUnload alwaysoff, aby uniknąć zapisu /NOUNLOAD za każdym razem gdy używasz tej samej wtyczki.

4.11.3 Ręczne Wywoływanie Wtyczek

Jeśli chcesz wywołać wtyczkę, która jest zapisana na dysku użytkownika lub gdzie indziej, użyj polecenia CallInstDLL. Prawie wszystkie wtyczki zgodne są z funkcjonalnością instalatora, więc używanie poleceń wtyczki jest łatwiejsze. Użycie polecenia CallInstDLL może być użyteczne, gdy utworzyłeś wtyczki, które powinny być linkowane do określonej wersji twojej aplikacji i które zostały skopiowane do katalogu instalacji.


4.12 Ciche (bezokienkowe) Instalatory/Deinstalatory

Ciche instalatory są instalatorami, które nie wymagają interakcji z użytkownikiem i nie posiadają interfejsu użytkownika. Użytkownik nie widzi żadnego okna dialogowego i nie są mu zadawana żadne pytania. Instalatory takie są przydatne dla administratorów sieci, którzy chcą szybko i sprawnie instalować lub deinstalować jakieś oprogramowanie na wielu komputerach, bez interwencji użytkownika. Użyteczne są również dla programistów, którzy chcą załączyć inny instalator do swojego i zebrać wszystkie wymagane informacje instalatora, bez potrzeby pokazywania dwu instalatorów.

Instalatory oraz deinstalatory NSIS mogą być zarówno ciche jak i okienkowe. Gdy instalator lub deinstalator jest cichy, nie wszystkie funkcje zwrotne są wywoływane. .onGUIInit, .onGUIEndoraz ich odpowiedniki w deinstalatorze, a takze każda funkcja zwrotna powiązana z określoną stroną lub jej typem nie zostanie wywołana.

Istnieje kilka metod na uczynienie instalatora lub deinstalatora cichym:

  1. SilentInstall oraz SilentUninstall
  2. SetSilent
  3. Użycie przełącznika /S w linii poleceń (wielkość liter ma znaczenie)

Aby sprawdzić czy instalator/deinstalator jest cichy użyj polecenia IfSilent.

Aby mieć pewność, że twój instalator będzie cichy, kiedy ma być, powinieneś sprawdzać to przy użyciu polecenia IfSilent, przed każdym poleceniem, które może wymagać interwencji użytkownika lub utworzenia okna. Polecenie MessageBox, które najczęściej powoduje problemy w cichych instalatorach, posiada przełącznik /SD, ustalajacy domyślną wartość odpowiedzi dla cichych instalatorów. Jeśli chcesz, aby twój instalator/deinstalator był całkowicie cichy, powinieneś użyć tego przełącznika. Wszystkie wewnętrzne okna dialogowe komunikatów w NSIS mają wartości domyślne dla cichych instalatorów. Przykład silent.nsi demonstruje wszystkei aspekty tego tematu.

Jako że, strona wyboru katalogu nie może być pokazana w cichych instalatorach, użytkownik ma możliwość okreslenia katalogu docelowego poprzez linię poleceń (opcja działa również w instalatorach/deinstalatorach okienkowych). Aby to zrobić, użytkownik musi użyć przełącznika /D, jak pokazano w przykładzie:

foo.exe /S /D=C:\Program Files\Foo

Jeśli twój instalator/deinstalator wymaga więcej informacji, których nie można pobrać w trybie cichym, możesz umożliwić użytkownikowi określić te informacje poprzez linię poleceń i wywołać je w funkcji .onInit. Możesz użyć funkcji GetOptions, lub jako wariant poniższego przykładu:

Function .onInit
  Call GetParameters
  Pop $2
  # szuka wyrażenia w cudzysłowiu: /USERNAME
  StrCpy $1 '"'
  Push $2
  Push '"/USERNAME='
  Call StrStr
  Pop $0
  StrCpy $0 $0 "" 1 # pomija znaki cudzysłowia
  Pop $0 "" "" next
    # szuka wyrażenia nie ujętego w cudzysłów: /USERNAME
    StrCpy $1 ' '
    Push $2
    Push '/USERNAME='
    Call StrStr
    Pop $0
next:
  Pop $0 "" done
    # kopiuje wartość po wyrażeniu /USERNAME=
    StrCpy $0 $0 "" 10
  # szuka następnego parametru
  Push $0
  Push $1
  Call StrStr
  Pop $1
  Pop $1 "" done
  StrLen $1 $1
  StrCpy $0 $0 -$1
done:
FunctionEnd

Powyższy przykład skopiuje wartość podaną przez użytkownika po parametrze /USERNAME= do zmiennej $0. Pozwala to na określenie wymaganych informacji w linii poleceń, zamiast używania interfejsu użytkownika. Użytkownik może użyć:

foo.exe /S /USERNAME=Bar /D=C:\Program Files\Foo

lub:

foo.exe /S "/USERNAME=łańcuch znaków z odstępami" /D=C:\Program Files\Foo

Funkcje GetParameters oraz StrStr można znaleźć w dodatku C.

Jesli twój instalator/deinstalator wymaga podania większej ilości informacji i chcesz skorzystać z trybu cichego , powinieneś umożliwić użytkownikowi dostęp do pliku z odpowiedziami. Powinno być to bardziej wygodne, niż zapisywanie wszystkich tych informacji w linii poleceń.


Poprzedni | Spis treści | Następny

Ostatnia aktualizacja strony: Niedziela, 6 Września 2009 (16:06:26)
Copyright © 2002 - 2010 by Paweł Porwisz. Wszelkie prawa zastrzeżone.
Strona wygenerowana w 0.011s. Hosted by tox.pl
[Valid XHTML] [Valid CSS] [Valid RSS] [Opera] [BrowseHappy]