Enumerate Process via CreateToolhelp32Snapshot - Delphi

DarkCoderSc personal avatar
DarkCoderSc

Jean-Pierre LESUEUR

// ...

uses
  System.SysUtils, Winapi.Windows, Winapi.TlHelp32, Generics.Collections;

// ...

function EnumerateRunningProcess(var AList : TList<TProcessEntry32>) : Cardinal;
begin
  result := 0;
  ///

  if not Assigned(AList) then
    AList := TList<TProcessEntry32>.Create()
  else
    AList.Clear();
  ///

  var hSnapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if hSnapshot = INVALID_HANDLE_VALUE then
    raise EWindowsException.Create('CreateToolhelp32Snapshot');
  try
    var AProcessEntry32 : TProcessEntry32;
    AProcessEntry32.dwSize := SizeOf(TProcessEntry32);

    if not Process32First(hSnapshot, AProcessEntry32) then
      raise EWindowsException.Create('Process32First');

    repeat
      AList.Add(AProcessEntry32);
    until Process32Next(hSnapshot, AProcessEntry32) = False;

    ///
    result := AList.Count;
  finally
    CloseHandle(hSnapshot);
  end;
end;

// ...

begin
  var AList := TList<TProcessEntry32>.Create();
  try
    EnumerateRunningProcess(AList);
    ///

    for var AProcessEntry in AList do
      WriteLn(Format('[%8d] -> %s', [
        AProcessEntry.th32ProcessID,
        AProcessEntry.szExeFile
      ]));
  finally
    FreeAndNil(AList);
  end;

// ...

Creating and researching code snippets takes time and effort. You’re welcome to share them through your own platforms, but please don’t forget to credit the original author, here: Jean-Pierre LESUEUR.

Depends On


Created

April 12, 2025

Last Revised

May 27, 2025