Articles   Members Online:
-Article/Tip Search
-News Group Search over 21 Million news group articles.
Member Area
-Account Center
-Top 10 NEW!!
-Submit Article/Tip
-Forums Upgraded!!
-My Articles
-Edit Information
-Become a Member
-Why sign up!
-Chat Online!
-Indexes NEW!!
-Build your resume
-Find a job
-Post a job
-Resume Search
-Link to us
Visit Embarcadero
Embarcadero Community
How to set environment variables Turn on/off line numbers in source code. Switch to Orginial background IDE or DSP color Comment or reply to this aritlce/tip for discussion. Bookmark this article to my favorite article(s). Print this article
Delphi 3.x
User Rating
No Votes
# Votes
DSP, Administrator
Reference URL:
			 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.


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 

1   function SetEnvVarValue(const VarName,
2     VarValue: string): Integer;
3   begin
4     // Simply call API function
5     if Windows.SetEnvironmentVariable(PChar(VarName),
6       PChar(VarValue)) then
7       Result := 0
8     else
9       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  var
13    ErrCode: Integer;
14  begin
15    ErrCode := SetEnvVarValue('FOO', 'Bar');
16    if ErrCode = 0 then
17      WinExec('MyChildProg.exe', SW_SHOWNORMAL);
18  else
19    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 here

Vote: How useful do you find this Article/Tip?
Bad Excellent
1 2 3 4 5 6 7 8 9 10


Share this page
Download from Google

Copyright © Mendozi Enterprises LLC