如何在程序运行时卸载程序,并且只有在用户确认关闭并卸载程序后才能卸载程序 - Inno Setup

时间:2016-06-30 13:28:43

标签: inno-setup uninstall

嘿,我需要在使用Inno Setup在Windows中运行时卸载我的程序。

我喜欢我的卸载程序检测,如果它正在运行并向用户提供一个消息框,例如“Windows 10 Logon Background Changer正在运行。是否要关闭它并卸载?”

上述消息框应该有两个按钮()。

当用户选择卸载此消息框后,即使它正在运行,当用户在消息框中选择时,卸载程序应该关闭。

如果用户在该消息框中选择,则卸载程序应该终止正在运行的程序进程并正常卸载(非静默)。

我编写了一个代码来执行此操作,但它失败并且它提供了错误的行为。

我的代码是:

function IsProcessRunning(const FileName: string): Boolean;
var
  FWMIService: Variant;
  FSWbemLocator: Variant;
  FWbemObjectSet: Variant;
begin
  Result := False;
  FSWbemLocator := CreateOleObject('WBEMScripting.SWBEMLocator');
  FWMIService := FSWbemLocator.ConnectServer('', 'root\CIMV2', '', '');
  FWbemObjectSet := FWMIService.ExecQuery(Format('SELECT Name FROM Win32_Process Where Name="%s"',[FileName]));
  Result := (FWbemObjectSet.Count > 0);
  FWbemObjectSet := Unassigned;
  FWMIService := Unassigned;
  FSWbemLocator := Unassigned;
end;

function InitializeUninstall(): Boolean;
  var ErrorCode: Integer;
begin
  Result := not IsProcessRunning('W10logbcr.exe');
  if not Result then
  Msgbox('Windows 10 Logon Background Changer is running.Do you like to close it automatically and uninstall?', mbError, MB_YESNO);
  if Msgbox('Windows 10 Logon Background Changer is running.Do you like to close it automatically and uninstall?', mbError, MB_YESNO) = IDNO then exit;
  if Msgbox('Windows 10 Logon Background Changer is running.Do you like to close it automatically and uninstall?', mbError, MB_YESNO) = IDYES then begin
    ShellExec('open','taskkill.exe','/f /im W10logbcr.exe','',SW_HIDE,ewNoWait,ErrorCode);
    ShellExec('open','tskill.exe',' Windows 10 Logon Background Changer ','',SW_HIDE,ewNoWait,ErrorCode);
    Result := True;
  end;
end;

如何更正超级错误代码?

提前致谢。

1 个答案:

答案 0 :(得分:1)

function IsProcessRunning(const AppName: string): Boolean;
var
  WMIService: Variant;
  WbemLocator: Variant;
  WbemObjectSet: Variant;
begin
  WbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
  WMIService := WbemLocator.ConnectServer('localhost', 'root\CIMV2');
  WbemObjectSet :=
    WMIService.ExecQuery('SELECT * FROM Win32_Process Where Name="' + AppName + '"');
  Result := not VarIsNull(WbemObjectSet) and (WbemObjectSet.Count > 0);
end;
const
  ExeName = 'W10logbcr.exe';

function InitializeUninstall(): Boolean;
var
  ErrorCode: Integer;
begin
  if IsProcessRunning(ExeName) then
  begin
    if MsgBox(
         'Windows 10 Logon Background Changer is running. ' +
         'Do you like to close it automatically and uninstall?',
         mbError, MB_YESNO) <> IDYES then
    begin
      Result := False;
      exit;
    end
      else
    begin
      ShellExec(
        'open', 'taskkill.exe', '/f /im ' + ExeName, '', SW_HIDE, ewNoWait, ErrorCode);
    end;
  end;

  Result := True;
end;

请注意,我已删除tskill.exe,因为我认为现在无关紧要。仅在Windows XP的Home版本甚至旧版Windows上都需要它。它实际上不再适用于Windows 10。

另请注意,我已将IsProcessRunning替换为implementation by @ariwez更好。