unit Environment;
interface
procedure ActivateEnvironmentVariables;
function AddGlobalEnvironmentVariable(
const Key:
string;
const Value :
string;
const now : boolean) : boolean;
function AddEnvironmentVariable(
const Key:
string;
const Value :
string;
const now : boolean) : boolean;
function DelGlobalEnvironmentVariable(
const Key:
string;
const now : boolean) : boolean;
function DelEnvironmentVariable(
const Key:
string;
const now : boolean) : boolean;
implementation
uses
Registry, Windows;
const
GlobalKey = '
System\CurrentControlSet\Control\Session Manager\Environment';
LocalKey = '
Environment';
WM_WININICHANGE = $001A;
procedure ActivateEnvironmentVariables;
begin
SendMessage(HWND_BROADCAST, WM_WININICHANGE, 0, LongInt(PChar('
Environment')));
end;
function AddGlobalEnvironmentVariable(
const Key:
string;
const Value :
string;
const now : boolean) : boolean;
var
Reg : TRegistry;
ok : boolean;
begin
Result := true;
ok := false;
try
Reg := TRegistry.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey(GlobalKey, false)
then
begin
Reg.WriteString(Key, Value);
Reg.CloseKey;
if now
then ActivateEnvironmentVariables;
ok := true;
end;
Result := ok;
except
Result := false;
end;
end;
function AddEnvironmentVariable(
const Key:
string;
const Value :
string;
const now : boolean) : boolean;
var
Reg : TRegistry;
ok : boolean;
begin
Result := true;
ok := false;
try
Reg := TRegistry.Create;
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey(LocalKey, false)
then
begin
Reg.WriteString(Key, Value);
Reg.CloseKey;
if now
then ActivateEnvironmentVariables;
ok := true;
end;
Result := ok;
except
Result := false;
end;
Result := SetEnvironmentVariable(PChar(Key), PChar(Value));
end;
function DelGlobalEnvironmentVariable(
const Key:
string;
const now : boolean) : boolean;
var
Reg : TRegistry;
ok : boolean;
begin
ok := false;
Result := true;
try
Reg := TRegistry.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey(GlobalKey, false)
then
begin
Reg.DeleteValue(Key);
Reg.CloseKey;
if now
then ActivateEnvironmentVariables;
ok := true;
end;
Result := ok;
except
Result := false;
end;
end;
function DelEnvironmentVariable(
const Key:
string;
const now : boolean) : boolean;
var
Reg : TRegistry;
ok : boolean;
begin
ok := false;
Result := true;
try
Reg := TRegistry.Create;
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKey(LocalKey, false)
then
begin
Reg.DeleteValue(Key);
Reg.CloseKey;
if now
then ActivateEnvironmentVariables;
ok := true;
end;
Result := ok;
except
Result := false;
end;
Result := SetEnvironmentVariable(PChar(Key),
nil);
end;
end.