function GetThreadID(const FileName: String): DWord;
var
ToolHnd, MToolHnd: THandle;
PE32: TProcessEntry32;
ME32: TModuleEntry32;
TE32: TThreadEntry32;
PIDArray, ThreadArray: Array of Dword;
a: Integer;
PID: DWord;
begin
PIDArray := nil;
ThreadArray := nil;
ToolHnd := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS or TH32CS_SNAPTHREAD, 0); //
Handle auf Snapshot
if ToolHnd = INVALID_HANDLE_VALUE then RaiseLastOSError;
try
PE32.dwSize := SizeOf(ProcessEntry32);
if not Process32First(ToolHnd, PE32) then RaiseLastOSError; //erster Prozess
repeat
if CompareText(PE32.szExeFile, ExtractFileName(FileName)) = 0 then
begin
SetLength(PIDArray, Length(PIDArray) + 1);
PIDArray[Length(PIDARRAY) - 1] := PE32.th32ProcessID;
end;
until not Process32Next(ToolHnd, PE32);
//ShowMessage(InttoStr(PIDArray[0]));
{ Jetzt sind alle PIDs der Prozesse, deren Dateinamen gleich dem gesuchten ist, gespeichert }
{ Jetzt wird für jeden Prozess anhand der Modulliste der vollständige Pfad ermittelt und so }
{ die endgültige, richtige ProcessID ermittelt. }
PID := 0;
for a := 0 to Length(PIDArray) -1 do
begin
MToolHnd := CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, PIDArray[a]); //Modulliste des gewählten Prozesses
if MToolHnd = INVALID_HANDLE_VALUE then RaiseLastOSError;
try
ME32.dwSize := SizeOf(TModuleEntry32);
if not Module32First(MToolhnd, ME32) then RaiseLastOSError;
repeat
if CompareText(ME32.szExePath, FileName) = 0 then
begin
PID := ME32.th32ProcessID;
Break;
end;
until not Module32Next(MToolHnd, ME32);
finally
CloseHandle(MToolHnd);
end;
if PID <> 0 then Break;
end;
//ShowMessage(IntToStr(PID));
{ Jetzt werden alle Threads des Prozesses ermittelt }
TE32.dwSize := SizeOf(ThreadEntry32);
if not Thread32First(ToolHnd, TE32) then RaiseLastOSError;
repeat
//Form1.Listbox1.Items.Add(InttoStr(TE32.th32OwnerProcessID) + 'Thread ' + InttoStr(TE32.th32ThreadID) + ' gehört zu Prozess ' + InttoStr(TE32.th32OwnerProcessID));
if TE32.th32OwnerProcessID = PID then
begin
SetLength(ThreadArray, Length(ThreadArray) + 1);
ThreadArray[Length(ThreadArray) - 1] := TE32.th32ThreadID;
end;
until not Thread32Next(ToolHnd, TE32);
finally
CloseHandle(ToolHnd);
end;
if Length(ThreadArray) > 0 then
begin
ShowMessage(IntToStr(ThreadArray[0]));
Result := ThreadArray[0];
end else Result := 0;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(IntToStr(GetThreadID('C:\Programme\Borland\Delphi6\Bin\Delphi32.exe')));
end;