2009. június 2., kedd

Reading and Writing System-Wide Environment Variables


Problem/Question/Abstract:

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.

function GetUserEnvironmentVariable(const name: string): string;
var
  rv: DWORD;
begin
  with TRegistry.Create do
  try
    RootKey := HKEY_CURRENT_USER;
    OpenKey('Environment', False);
    result := ReadString(name);
    SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, LParam
      (PChar('Environment')), SMTO_ABORTIFHUNG, 5000, rv);
  finally
    Free
  end
end;

procedure SetUserEnvironmentVariable(const name, value: string);
var
  rv: DWORD;
begin
  with TRegistry.Create do
  try
    RootKey := HKEY_CURRENT_USER;
    OpenKey('Environment', False);
    WriteString(name, value);
    SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, LParam
      (PChar('Environment')), SMTO_ABORTIFHUNG, 5000, rv);
  finally
    Free
  end
end;

The next two procedures read and write environment variables for the system and thus
  affect all users.

function GetSystemEnvironmentVariable(const name: string): string;
var
  rv: DWORD;
begin
  with TRegistry.Create do
  try
    RootKey := HKEY_LOCAL_MACHINE;
    OpenKey('SYSTEM\CurrentControlSet\Control\Session ' +
      'Manager\Environment', False);
    result := ReadString(name);
    SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, LParam
      (PChar('Environment')), SMTO_ABORTIFHUNG, 5000, rv);
  finally
    Free
  end
end;

// Modified from
// http://www.delphiabc.com/TipNo.asp?ID=117
// The original article did not include the space in
// "Session Manager" which caused the procedure to fail.

procedure SetSystemEnvironmentVariable(const name, value: string);
var
  rv: DWORD;
begin
  with TRegistry.Create do
  try
    RootKey := HKEY_LOCAL_MACHINE;
    OpenKey('SYSTEM\CurrentControlSet\Control\Session ' +
      'Manager\Environment', False);
    WriteString(name, value);
    SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, LParam
      (PChar('Environment')), SMTO_ABORTIFHUNG, 5000, rv);
  finally
    Free
  end
end;

Nincsenek megjegyzések:

Megjegyzés küldése