2007. június 10., vasárnap

Setting environment variables


Problem/Question/Abstract:

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.

function SetEnvVarValue(const VarName,
  VarValue: string): Integer;
begin
  // Simply call API function
  if Windows.SetEnvironmentVariable(PChar(VarName),
    PChar(VarValue)) then
    Result := 0
  else
    Result := GetLastError;
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:

{ snip ... }
var
  ErrCode: Integer;
begin
  ErrCode := SetEnvVarValue('FOO', 'Bar');
  if ErrCode = 0 then
    WinExec('MyChildProg.exe', SW_SHOWNORMAL);
else
  ShowMessage(SysErrorMessage(ErrCode));
end;
{ ... 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 here.

Nincsenek megjegyzések:

Megjegyzés küldése