[转载]Inno Setup 安装、卸载前检测进程或服务

(2015-04-24 17:37:20)
标签:

转载

 

 

  在用Inno打包期间遇到了一些小问题,在这里总结一下:
 
Inno.iss部分内容如下:

1、32位程序的PSVince.dll插件方法。
[Files]
Source: psvince.dll; Flags: dontcopy

[Code]
function IsModuleLoaded(modulename: AnsiString ):  Boolean;
external 'IsModuleLoaded@files:psvince.dll stdcall';
2、PSVince控件在64位系统(Windows 7/Server 2008/Server 2012)下无法检测到进程,使用下面的函数可以解决。
function IsAppRunning(const FileName : string): Boolean;
var
    FSWbemLocator: Variant;
    FWMIService   : Variant;
    FWbemObjectSet: Variant;
begin
    Result := false;
    try
      FSWbemLocator := CreateOleObject('WBEMScripting.SWBEMLocator');
      FWMIService := FSWbemLocator.ConnectServer('', 'rootCIMV2', '', '');
      FWbemObjectSet := FWMIService.ExecQuery(Format('SELECT Name FROM Win32_Process Where Name="%s"',[FileName]));
      Result := (FWbemObjectSet.Count > 0);
      FWbemObjectSet := Unassigned;
      FWMIService := Unassigned;
      FSWbemLocator := Unassigned;
    except
      if (IsModuleLoaded(FileName)) then
        begin
          Result := false;
        end
      else
        begin
          Result := true;
        end
      end;
end;
这里,有可能存在异常:Exception: SWbemLocator:依赖服务或组件无法启动
解决办法参照如下步骤
1.在命令提示行运行以下命令:
    cd /d %windir%system32wbem 
    rename Repository Rep_bak 
2.建一个.bat批处理文件并运行,内容如下: 
    Mofcomp C:WINDOWSsystem32WBEMcimwin32.mof
    Mofcomp C:WINDOWSsystem32WBEMcimwin32.mfl
    Mofcomp C:WINDOWSsystem32WBEMsystem.mof
    Mofcomp C:WINDOWSsystem32WBEMwmipcima.mof
    Mofcomp C:WINDOWSsystem32WBEMwmipcima.mfl
3.在命令提示行运行以下命令:
    cd /d %windir%system32wbem 
    for %i in (*.mof,*.mfl) do Mofcomp %i 
4.重新注册 WMI 组件,在命令提示行运行以下命令:
    cd /d %windir%system32wbem 
    for %i in (*.dll) do RegSvr32 -s %i 
    for %i in (*.exe) do %i /RegServer 

//安装,并在安装前检测程序是否在运行,如果运行先结束进程
function InitializeSetup(): Boolean;
begin
  Result := true;
  if  IsAppRunning('{#MyAppExeName}') then
  begin
    if MsgBox('安装程序检测到 {#MyAppName} 正在运行!'#13''#13'单击“是”按钮关闭程序并继续安装;'#13''#13'单击“否”按钮退出安装!', mbConfirmation, MB_YESNO) = IDYES then
    begin
      TaskKillProcessByName('{#MyAppExeName}');
      Result:= true;
    end
    else
      Result:= false;
  end;
end;
//卸载,与安装类似
function InitializeUninstall(): Boolean;
  begin
    Result:= true;
    if  IsAppRunning('{#MyAppExeName}') then
    begin
      if MsgBox('卸载程序检测到 {#MyAppName} 正在运行!'#13''#13'单击“是”按钮关闭程序并继续卸载;'#13''#13'单击“否”按钮退出卸载!', mbConfirmation, MB_YESNO) = IDYES then
      begin
        TaskKillProcessByName('{#MyAppExeName}');
        Result:= true;
      end
      else
        Result:= false;
    end;
  end;