I am trying to get a process count starting with the full name of the executable.
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;
GetPathFromPIDthe function was taken from here (answer by Andreas Regbrand).
Running the application, I got an EOSError exception ('System Error. Code: 87.'). As the documentation says:
ERROR_INVALID_PARAMETER
87 (0x57)
Invalid parameter.
An exception arises from the function GetPathFromPIDbecause the condition hProcess <> 0fails and is satisfied RaiseLastOSError.
Debugging I noticed that 0 is passed to the function GetPathFromPIDas a PID parameter, but I don't understand what is wrong in my code.
source
share