Shambhala
Shambhala

Reputation: 1169

TProcessInfo - Get fullpath of processes

I am using this non visual open source component called TProcessInfo to get a list of processes, the ProcessID and the full path which I put into a ListView.

The code I am using to do this:

procedure TForm1.FormCreate(Sender: TObject);
var
  i: integer;
  Process: TProcessItem;
begin
  for i := 0 to ProcessInfo1.RunningProcesses.Count -1 do
  begin
    Process := ProcessInfo1.RunningProcesses[i];
    with lv.Items.Add do
    begin
      Caption := Process.ExeFile;
      SubItems.Add(IntToStr(Process.ProcessID));
      SubItems.Add(Process.FullPath);
    end;
  end;
end;

The code will always break on the last line: SubItems.Add(Process.FullPath); and I receive an Error Message:

System Error. Code: 87
The Parameter is incorrect.

The code that gets the FullPath in the Component is:

function TProcessItem.GetFullPath: TFileName;
var
  hProcess: THandle;
begin
  hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ,False,FProcessID);
  if hProcess <> 0 then
  begin
    try
      SetLength(Result,MAX_PATH);
      FillChar(Result[1],Length(Result) * SizeOf(Char), 0);
      if GetModuleFileNameEx(hProcess,0,PChar(Result),Length(Result)) > 0 then
        Result := Trim(Result)
      else
       RaiseLastOSError;
    finally
      CloseHandle(hProcess)
    end;
  end
  else
    RaiseLastOSError;
end;

If like the Error states - the parameter is incorrect, then how can I change this?

** The component uses PsAPI and I am using Delphi XE2 on Windows 7 Ultimate x64 also happens on Windows XP Pro x86

Upvotes: 1

Views: 4034

Answers (1)

Slava Zhuyko
Slava Zhuyko

Reputation: 711

This happens because "System Idle Process" has PID = 0 and OpenProcess fails with such a ProcessID value. Patch the library to avoid using it or uset try/except in your loop.

Upvotes: 5

Related Questions