Inno Setup安裝卸載時檢查程序是否運行提示並中止程序

Inno Setup打包的軟件需要在安裝和卸載時檢查程序是否在運行,不然會安裝失敗或者卸載不完全,網上搜了一下,有幾種方法:

1. 自己封裝DLL,或者下載別人寫好的DLL,比如psvince.dll和ISTask.dll,判斷程序是否運行然後中止(有人說調用很慢很卡,沒驗證,因爲自己沒下載這兩個DLL,自己寫覺得麻煩)

2. 通過FindWindowByWindowName之類的函數查找窗口,然後發送消息,通知程序退出(窗口名不固定就很麻煩,還有查找不到的)

3. 通過調用命令行,執行windwow命令,達到檢查和中止的功能(調用cmd命令會被一些殺毒軟件阻止,需要手動允許)

4. 通過在程序中添加命名mutex,然後在iss腳本中通過CheckForMutexes等函數判斷程序是否運行

我使用的是第3種方法

在iss腳本的[Code]段添加如下代碼,自己替換 “你的軟件名.exe” 成你要檢查的exe名稱

[Code]

// 自定義函數,判斷軟件是否運行,參數爲需要判斷的軟件的exe名稱
function KDetectSoft(strExeName: String): Boolean;
// 變量定義
var ErrorCode: Integer;
var bRes: Boolean;
var strFileContent: AnsiString;
var strTmpPath: String;  // 臨時目錄
var strTmpFile: String;  // 臨時文件,保存查找軟件數據結果
var strCmdFind: String;  // 查找軟件命令
var strCmdKill: String;  // 終止軟件命令
begin
  strTmpPath := GetTempDir();
  strTmpFile := Format('%sfindSoftRes.txt', [strTmpPath]);
  strCmdFind := Format('/c tasklist /nh|find /c /i "%s" > "%s"', [strExeName, strTmpFile]);
  strCmdKill := Format('/c taskkill /f /t /im %s', [strExeName]);
  //ShellExec('open', ExpandConstant('{cmd}'), '/c taskkill /f /t /im 你的軟件名.exe', '', SW_HIDE, ewNoWait, ErrorCode);
  //bRes := ShellExec('open', ExpandConstant('{cmd}'), '/c tasklist /nh|find /c /i "你的軟件名.exe" > 0.txt', '', SW_HIDE, ewWaitUntilTerminated, ErrorCode);
  bRes := ShellExec('open', ExpandConstant('{cmd}'), strCmdFind, '', SW_HIDE, ewWaitUntilTerminated, ErrorCode);
  if bRes then begin
      bRes := LoadStringFromFile(strTmpFile, strFileContent);
      strFileContent := Trim(strFileContent);
      if bRes then begin
         if StrToInt(strFileContent) > 0 then begin
            if MsgBox(ExpandConstant('{cm:checkSoftTip}'), mbConfirmation, MB_OKCANCEL) = IDOK then begin
             // 終止程序
             ShellExec('open', ExpandConstant('{cmd}'), strCmdKill, '', SW_HIDE, ewNoWait, ErrorCode);
             Result:= true;// 繼續安裝
            end else begin
             Result:= false;// 安裝程序退出
             Exit;
            end;
         end else begin
            //MsgBox('軟件沒在運行', mbInformation, MB_OK);
            Result:= true;
            Exit;
         end;
      end;
  end;
  Result :=true;
end;


// 開始頁下一步時判斷軟件是否運行
function NextButtonClick(CurPageID: Integer): Boolean;
begin
  if 1=CurPageID then begin
      Result := KDetectSoft('你的軟件名.exe');
      Exit;
  end; 
  Result:= true;
end;

      
// 卸載時關閉軟件
function InitializeUninstall(): Boolean;
begin
  Result := KDetectSoft('你的軟件名.exe');
end;

腳本是支持中英文安裝包,所以還要添加[CustomMessages]段

; 自定義不同語言文本
[CustomMessages]
english.checkSoftTip=Setup detects that the software to be installed is running!%n%nClick "ok" to continue the operation after terminating the software, otherwise click "cancel" .
chinesesimp.checkSoftTip=安裝程序檢測到將安裝的軟件正在運行!%n%n點擊"確定"終止軟件後繼續操作,否則點擊"取消"。

如果不用支持中英文,可以把上面函數裏的ExpandConstant('{cm:checkSoftTip}')直接改成你要顯示的提示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章