在Inno setup中安装时添加环境变量以及卸载时删除环境变量,需要注意的问题已经在文档中进行说明
// 设置环境变量函数
procedure SetEnv(aEnvName, aEnvValue: string; aIsInstall, aIsInsForAllUser: Boolean);
var
sOrgValue: string;
sFileName: string;
S1: AnsiString; //注意类型是AnsiString,不是string
bRetValue, bInsForAllUser: Boolean;
SL: TStringList;
x: integer;
begin
bInsForAllUser := aIsInsForAllUser;
if UsingWinNT then
begin
if bInsForAllUser then
bRetValue := RegQueryStringValue(HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', aEnvName, sOrgValue)
else
bRetValue := RegQueryStringValue(HKEY_CURRENT_USER, 'Environment', aEnvName, sOrgValue);
sOrgValue := Trim(sOrgValue);
begin
S1 := aEnvValue;
if pos(Uppercase(s1), Uppercase(sOrgValue)) = 0 then //还没有加入
begin
if aIsInstall then
begin
x := Length(sOrgValue);
if (x > 0) and (StringOfChar(sOrgValue[x], 1) <> ';') then
sOrgValue := sOrgValue + ';';
sOrgValue := sOrgValue + S1;
end;
end else
begin
if not aIsInstall then
begin
StringChangeEx(sOrgValue, S1 + ';', '', True);
StringChangeEx(sOrgValue, S1, '', True);
end;
end;
if bInsForAllUser then
RegWriteStringValue(HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', aEnvName, sOrgValue)
else
begin
if (not aIsInstall) and (Trim(sOrgValue) = '') then
RegDeleteValue(HKEY_CURRENT_USER, 'Environment', aEnvName)
else
RegWriteStringValue(HKEY_CURRENT_USER, 'Environment', aEnvName, sOrgValue);
end;
end;
end else //非NT 系统,如Win98
begin
SL := TStringList.Create;
try
sFileName := ExpandConstant('{sd}\autoexec.bat');
LoadStringFromFile(sFileName, S1);
SL.Text := s1;
s1 := '"' + aEnvValue + '"';
s1 := 'set '+aEnvName +'=%path%;' + s1 ;
bRetValue := False;
x := SL.IndexOf(s1);
if x = -1 then
begin
if aIsInstall then
begin
SL.Add(s1);
bRetValue := True;
end;
end else //还没添加
if not aIsInstall then
begin
SL.Delete(x);
bRetValue := True;
end;
if bRetValue then
SL.SaveToFile(sFileName);
finally
SL.free;
end;
end;
end;
// 安装前添加环境变量
procedure CurStepChanged(CurStep: TSetupStep);
begin
if CurStep = ssInstall then //对于(ssInstall)这个变量可依据自身需要进行更改,帮助文档中有说明(也可是安装完成之后进行写入对应变量为ssDone)
begin
// 将{app}路径添加到path环境变量中
SetEnv('path',ExpandConstant('{app};'),true,true); //对于添加多个环境变量需要注意要添加分割符号";",否则系统会认为是一个
SetEnv('path',ExpandConstant('{app}\ddd'),true,true); //在这儿调用,一定在这儿调用,安装完无须重启,立即生效
end;
end;
// 卸载前删除环境变量
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
begin
// 将{app}路径从path环境变量中删除
SetEnv('path',ExpandConstant('{app};'),false,true);
SetEnv('path',ExpandConstant('{app}\ddd'),false,true); //卸载时所需要删除的环境变量需要与所添加的变量一致,以免误删除
end;
另外关于Inno setup安装包的问题大家可以一起交流