Einzelnen Beitrag anzeigen

NicoDE
(Gast)

n/a Beiträge
 
#4

Re: Voller Pfad einer Anwendung anhand Handle

  Alt 5. Aug 2004, 20:50
Delphi-Quellcode:
uses
  TlHelp32, PsAPI;

function GetWindowProcessImageFileName(Wnd: HWND): string;
const
  DesiredAccess = PROCESS_QUERY_INFORMATION or PROCESS_VM_READ;
var
  ProcessId: DWORD;
  Snapshot: THandle;
  ModuleEntry: TModuleEntry32;
  Process: DWORD;
  Module: HMODULE;
  Needed: DWORD;
  FileName: array [0..MAX_PATH-1] of Char;
begin
  SetLength(Result, 0);
  ProcessId := 0;
  GetWindowThreadProcessId(Wnd, ProcessId);
  if 0 = ProcessId then
    Exit;

  // Windows 95, Windows 2000
  Snapshot := CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, ProcessId);
  if (Snapshot <> 0) and (Snapshot <> INVALID_HANDLE_VALUE) then
    try
      ModuleEntry.dwSize := SizeOf(TModuleEntry32);
      if Module32First(Snapshot, ModuleEntry) then
        Result := StrPas(ModuleEntry.szExePath);
    finally
      CloseHandle(Snapshot);
    end
  else
  begin
    // Windows NT 4.0
    Process := OpenProcess(DesiredAccess, False, ProcessId);
    if Process <> 0 then
      try
        if EnumProcessModules(Process, PDWORD(Addr(Module)), SizeOf(HMODULE),
          Needed) and (GetModuleFileNameEx(Process, Module, FileName,
          SizeOf(FileName)) > 0) then
          Result := StrPas(FileName);
      finally
        CloseHandle(Process);
      end;
  end;
end;
BTW, das Snapshot-Handle nur auf ungleich INVALID_HANDLE_VALUE abzufragen ist unsicher/falsch, da der Wrapper in der TlHelp32.pas 0 zurückgibt falls die API nicht vorhanden ist.
  Mit Zitat antworten Zitat