I'm trying to get the process count starting from an executable full file name.
Here is my code:
function GetPathFromPID(const PID: cardinal): string;
var
hProcess: THandle;
path: array[0..MAX_PATH - 1] of char;
begin
hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, false, PID);
if hProcess <> 0 then
try
if GetModuleFileNameEx(hProcess, 0, path, MAX_PATH) = 0 then
RaiseLastOSError;
result := path;
finally
CloseHandle(hProcess)
end
else
RaiseLastOSError;
end;
function ProcessCount(const AFullFileName: string): Integer;
var
ContinueLoop: boolean;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
Result := 0;
while(ContinueLoop) do
begin
if ((UpperCase(GetPathFromPID(FProcessEntry32.th32ProcessID)) = UpperCase(AFullFileName)))
then Result := Result + 1;
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Self.Caption := IntToStr(ProcessCount(Application.ExeName));
end;
GetPathFromPID
function has been taken from here (Andreas Rejbrand's answer).
Running the application, I got EOSError exception ('System Error. Code: 87.'). As documentation says:
ERROR_INVALID_PARAMETER
87 (0x57)
The parameter is incorrect.
The exception is raised from GetPathFromPID
function, because the hProcess <> 0
condition fails and RaiseLastOSError
is executed.
Debugging I've noticed that 0 is passed to GetPathFromPID
function as PID parameter but I don't understand what's wrong in my code.