Search code examples
environment-variablesinno-setuppascalscript

How to set registry key (environment variable) with value from [Code] section of Inno Setup?


I'm creating an installer with Inno Setup, and I need to set the Environment Variable for the user if they didn't set yet.

What I exactly want to achieve is as follows :

  1. Detect whether the system has the Environment Variable called "JAVA_HOME" or not.

  2. If it already has, then skip the remaining steps. If not, then I will show a page to prompt the user to input the path where they install the JDK, and set to the value of the Environment Variable.

And my problem is : How would I set the Environment Variable according to the value input by user? I've searched some articles, and the only way I found to set Environment Variable is like this

[Registry]
; set PATH
Root: HKLM; Subkey: "Environment"; ValueType:string; ValueName:"VARIABLE_NAME"; \
    ValueData:"new_value" ; Flags: preservestringtype ;

But obviously, that couldn't achieve what I want to do, because the value must be written "Before" the installer been built. So could any one has any device? Thanks!


Solution

  • You do not need a code to set the registry key (= environment variable). You just need to get the registry key value (= environment variable value) from the code.

    You are looking for a scripted constant:

    [Registry]
    Root: HKLM; Subkey: "Environment"; ValueType: string; ValueName: "VARIABLE_NAME"; \
        ValueData: "{code:GetJDKPath}"; Flags: preservestringtype;
    
    [Code]
    
    var
      { A global variable that contains the path provided by the user in step 2 }
      JDKPath: string;
    
    function GetJDKPath(Param: string): string;
    begin
      Result := JDKPath;
    end;