Author: Peter Johnson
There have been various articles showing how to access the environment variables.
This article shows how to create, modify and delete an environment variable.
Answer:
The following simple routine stores a new value in an environment variable. If the
the environment variable doesn't exists then it is created. Setting an environment
variable to the empty string deletes the variable. The function returns 0 if the
variable is set / created successfully, or returns a Windows error code on failure.
Note that there is a limit on the amount of space available for environment
variables.
1 function SetEnvVarValue(const VarName,
2 VarValue: string): Integer;
3 begin4 // Simply call API function5 if Windows.SetEnvironmentVariable(PChar(VarName),
6 PChar(VarValue)) then7 Result := 0
8 else9 Result := GetLastError;
10 end;
It should be noted that changes to environment variables only apply to the current
process or to any child processes spawned by the current process.
To pass a custom environment variable to a child process simply:
Create the new environment variable using SetDOSEnvVar.
Execute the new program.
So, to pass the current environment + a an environment variable FOO=Bar to a child
process do:
11 { snip ... }12 var13 ErrCode: Integer;
14 begin15 ErrCode := SetEnvVarValue('FOO', 'Bar');
16 if ErrCode = 0 then17 WinExec('MyChildProg.exe', SW_SHOWNORMAL);
18 else19 ShowMessage(SysErrorMessage(ErrCode));
20 end;
21 { ... end snip }
The new program can access the new variable using any of the techniques described
in other articles.
It is also possible to pass a custom environment variable block to another process.
The method for doing this is covered by another article.
A demo program that demonstrates this and other environment variable techniques is available for download herehttp://www.delphidabbler.com/download.php?file=envvardemo.zip.