Author: Richard Winston
How do you set an environment variable that will apply outside the process that set
the variable or those spawned by it?
Answer:
On Windows 2000, if you open the control panel and double click on the system icon,
the system properties dialog box will open. On the "Advanced" tab, you can click
the "Environment Variables" tab to see a list of the user and system environment
variables. The procedures and functions below allow you to read and write those
variables.
It is worth mentioning that you can also use "GetEnvironmentVariable" and
"SetEnvironmentVariable" to read and write environment variables. However, if you
set and environment variable with "SetEnvironmentVariable", the value you set
applies only to the process that called "SetEnvironmentVariable" or are spawned by
it.
The first two procedures read and write environment variables for the current user.
1
2 function GetUserEnvironmentVariable(const name: string): string;
3 var
4 rv: DWORD;
5 begin
6 with TRegistry.Create do
7 try
8 RootKey := HKEY_CURRENT_USER;
9 OpenKey('Environment', False);
10 result := ReadString(name);
11 SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, LParam
12 (PChar('Environment')), SMTO_ABORTIFHUNG, 5000, rv);
13 finally
14 Free
15 end
16 end;
17
18 procedure SetUserEnvironmentVariable(const name, value: string);
19 var
20 rv: DWORD;
21 begin
22 with TRegistry.Create do
23 try
24 RootKey := HKEY_CURRENT_USER;
25 OpenKey('Environment', False);
26 WriteString(name, value);
27 SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, LParam
28 (PChar('Environment')), SMTO_ABORTIFHUNG, 5000, rv);
29 finally
30 Free
31 end
32 end;
The next two procedures read and write environment variables for the system and thus
affect all users.
33
34 function GetSystemEnvironmentVariable(const name: string): string;
35 var
36 rv: DWORD;
37 begin
38 with TRegistry.Create do
39 try
40 RootKey := HKEY_LOCAL_MACHINE;
41 OpenKey('SYSTEM\CurrentControlSet\Control\Session ' +
42 'Manager\Environment', False);
43 result := ReadString(name);
44 SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, LParam
45 (PChar('Environment')), SMTO_ABORTIFHUNG, 5000, rv);
46 finally
47 Free
48 end
49 end;
50
51 // Modified from
52 // http://www.delphiabc.com/TipNo.asp?ID=117
53 // The original article did not include the space in
54 // "Session Manager" which caused the procedure to fail.
55
56 procedure SetSystemEnvironmentVariable(const name, value: string);
57 var
58 rv: DWORD;
59 begin
60 with TRegistry.Create do
61 try
62 RootKey := HKEY_LOCAL_MACHINE;
63 OpenKey('SYSTEM\CurrentControlSet\Control\Session ' +
64 'Manager\Environment', False);
65 WriteString(name, value);
66 SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, LParam
67 (PChar('Environment')), SMTO_ABORTIFHUNG, 5000, rv);
68 finally
69 Free
70 end
71 end;
|