Inno Setup Pascal Script to search for running process

笑着哭i 提交于 2019-11-30 22:13:15
TLama

This is an exemplary task for WMI and its WQL language. Getting list of running processes through WMI is even more reliable than Windows API. The below example shows how to query the Win32_Process class with the LIKE operator:

[Setup]
AppName=My Program
AppVersion=1.5
DefaultDirName={pf}\My Program
DefaultGroupName=My Program

[Code]
type
  TProcessEntry = record
    PID: DWORD;
    Name: string;
    Description: string;
    ExecutablePath: string;
  end;
  TProcessEntryList = array of TProcessEntry;

function GetProcessList(const Filter: string;
  out List: TProcessEntryList): Integer;
var
  I: Integer;
  WQLQuery: string;
  WbemLocator: Variant;
  WbemServices: Variant;
  WbemObject: Variant;
  WbemObjectSet: Variant;
begin
  Result := 0;

  WbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
  WbemServices := WbemLocator.ConnectServer('localhost', 'root\CIMV2');

  WQLQuery :=
    'SELECT ' +
    'ProcessId, ' + 
    'Name, ' + 
    'Description, ' + 
    'ExecutablePath ' +
    'FROM Win32_Process ' +
    'WHERE ' +
    'Name LIKE "%'+ Filter +'%"';

  WbemObjectSet := WbemServices.ExecQuery(WQLQuery);
  if not VarIsNull(WbemObjectSet) and (WbemObjectSet.Count > 0) then
  begin
    Result := WbemObjectSet.Count;
    SetArrayLength(List, WbemObjectSet.Count);
    for I := 0 to WbemObjectSet.Count - 1 do
    begin
      WbemObject := WbemObjectSet.ItemIndex(I);
      if not VarIsNull(WbemObject) then
      begin
        List[I].PID := WbemObject.ProcessId;
        List[I].Name := WbemObject.Name;
        List[I].Description := WbemObject.Description;
        List[I].ExecutablePath := WbemObject.ExecutablePath;
      end;
    end;
  end;
end;

procedure InitializeWizard;
var
  S: string;
  I: Integer;
  Filter: string;
  ProcessList: TProcessEntryList;
begin
  MsgBox('Now we try to list processes containing "sv" in their names...',
    mbInformation, MB_OK);

  Filter := 'sv';
  if GetProcessList(Filter, ProcessList) > 0 then
    for I := 0 to High(ProcessList) do
    begin
      S := Format(
        'PID: %d' + #13#10 +
        'Name: %s' + #13#10 +
        'Description: %s' + #13#10 +
        'ExecutablePath: %s', [
        ProcessList[I].PID,
        ProcessList[I].Name,
        ProcessList[I].Description,
        ProcessList[I].ExecutablePath]);
      MsgBox(S, mbInformation, MB_OK);
    end;
end;

If not work.Please change as follows.

(old) for I := 0 to High(ProcessList) do

(new) for I := 0 to (GetArrayLength(ProcessList) - 1) do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!