Einzelnen Beitrag anzeigen

Benutzerbild von KodeZwerg
KodeZwerg

Registriert seit: 1. Feb 2018
3.685 Beiträge
 
Delphi 11 Alexandria
 
#23

AW: In welchem Pfad läuft ein Prozess?

  Alt 21. Okt 2018, 09:30
Delphi-Quellcode:
function PidToFilename(const TargetPID: THandle): WideString;
type
  TQueryFullProcessImageNameW = function(AProcess: THANDLE; AFlags: DWORD; lpExeName: PWideChar; var nSize: DWORD): BOOL; stdcall;
var
  hProcess: THandle;
  TargetName: array [0 .. MAX_PATH - 1] of WideChar;
  QueryFullProcessImageNameW: TQueryFullProcessImageNameW;
  nSize: DWORD;
begin
  Result := '';
  hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, false, TargetPID);
  if hProcess <> 0 then
    try
      if GetModuleFileNameExW(hProcess, 0, TargetName, MAX_PATH) <> 0 then Result := TargetName
      else if Win32MajorVersion >= 6 then
      begin
        nSize := MAX_PATH;
        ZeroMemory(@TargetName, MAX_PATH);
        @QueryFullProcessImageNameW := GetProcAddress(GetModuleHandle('kernel32'), 'QueryFullProcessImageNameW');
        if Assigned(QueryFullProcessImageNameW) then
          if QueryFullProcessImageNameW(hProcess, 0, TargetName, nSize) then Result := TargetName
      end;
    finally
      CloseHandle(hProcess);
    end;
end;

function ProcessExists(const AFileName: WideString; var FoundFiles: TStringList; out HostIndex: Integer): Boolean;
var
  ContinueLoop: BOOL;
  FSnapshotHandle: THandle;
  FProcessEntry32: TProcessEntry32;
  fullPath: WideString;
  myPID: DWORD;
  OwnPID: Cardinal;
begin
  HostIndex := -1;
  FoundFiles := TStringList.Create;
  OwnPID := GetCurrentProcessId;
  FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
  ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
  Result := False;
  while Integer(ContinueLoop) <> 0 do
  begin
    if UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) = UpperCase(ExtractFileName(AFileName)) then
    begin
      myPID := FProcessEntry32.th32ProcessID;
      fullPath := PidToFilename(myPID);
      FoundFiles.Add(fullPath);
      if myPID = OwnPID then
      begin
        HostIndex := FoundFiles.Count-1;
        Result := True;
      end;
    end;
    ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
  end;
  CloseHandle(FSnapshotHandle);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  s: TStringList;
  i, idx: Integer;
begin
  Memo1.Clear;
  processExists(Edit1.Text, S, idx);
  for i := 0 to S.Count -1 do
    Memo1.Lines.Add(S.Strings[i]);
  if (idx >= 0) then Memo1.Lines.Add('Host is '+S.Strings[idx]);
end;
In der Hoffnung das ich dieses mal alles berücksichtigt habe was man so alles berücksichtigen sollte für Delphi's vor 2009.
Gruß vom KodeZwerg

Geändert von KodeZwerg (21. Okt 2018 um 09:50 Uhr)
  Mit Zitat antworten Zitat