По идентификатору (PID) процесса, получаем путь к его исполняемому файлу.
[Получить ID процесса по его имени]
1 2 3 4 5 6 7 8 |
var pid: Integer; exePath: string; begin pid:= 880; exePath:= GetFilePathByProcessID(pid); ShowMessage(exePath); end; |
Параметры
pid - идентификатор (PID) процесса
Результат
Путь к файлу процесса или пустая строка, в случае неудачи или если процесс не существует.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
function GetFilePathByProcessID(AProcessID: DWORD): UnicodeString; type TQueryFullProcessImageNameW = function(AProcess: THANDLE; AFlags: DWORD; AFileName: PWideChar; var ASize: DWORD): BOOL; stdcall; TGetModuleFileNameExW = function(AProcess: THANDLE; AModule: HMODULE; AFilename: PWideChar; ASize: DWORD): DWORD; stdcall; const PROCESS_QUERY_LIMITED_INFORMATION = $00001000; var HProcess: THandle; Lib: HMODULE; QueryFullProcessImageNameW: TQueryFullProcessImageNameW; S: DWORD; var PsapiLib: HMODULE; GetModuleFileNameExW: TGetModuleFileNameExW; filescnt: Integer; NetShareEnumNT:function(servername:PWChar; level:DWORD; bufptr:Pointer; prefmaxlen:DWORD; entriesread, totalentries, resume_handle:LPDWORD): DWORD; stdcall; begin if Win32MajorVersion >= 6 then begin Result:= ''; Lib := GetModuleHandle('kernel32.dll'); if Lib = 0 then Exit; @QueryFullProcessImageNameW := GetProcAddress(Lib, 'QueryFullProcessImageNameW'); if not Assigned(QueryFullProcessImageNameW) then Exit; HProcess := OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, AProcessID); if HProcess = 0 then exit; try S := MAX_PATH; SetLength(Result, S + 1); while not QueryFullProcessImageNameW(HProcess, 0, PWideChar(Result), S) and (GetLastError = ERROR_INSUFFICIENT_BUFFER) do begin S := S * 2; SetLength(Result, S + 1); end; SetLength(Result, S); Inc(S); if not QueryFullProcessImageNameW(HProcess, 0, PWideChar(Result), S) then Exit; finally CloseHandle(HProcess); end; end else if Win32MajorVersion >= 5 then begin if PsapiLib <> 0 then Exit; PsapiLib := LoadLibrary('psapi.dll'); if PsapiLib = 0 then Exit; @GetModuleFileNameExW := GetProcAddress(PsapiLib, 'GetModuleFileNameExW'); if not Assigned(GetModuleFileNameExW) then try Exit; except if PsapiLib = 0 then Exit; FreeLibrary(PsapiLib); PsapiLib := 0; @GetModuleFileNameExW := nil; raise; end; HProcess := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, AProcessID); if HProcess = 0 then Exit; try S := MAX_PATH; SetLength(Result, S + 1); if GetModuleFileNameExW(HProcess, 0, PWideChar(Result), S) = 0 then Exit; Result := PWideChar(Result); finally CloseHandle(HProcess); end; end; end; |