How to get PID of last created thread in process

delphi package - getting into other processes
Post Reply
beBoss
Posts: 1
Joined: Tue Apr 14, 2009 10:03 pm

How to get PID of last created thread in process

Post by beBoss »

How to get PID of last created thread in process ?

i use function to get first :

Code: Select all

function GetThreadID(ProcessID : DWORD ) : DWORD ;
var
    Handle:tHandle;
   ThreadEntry : ThreadEntry32;
  GotThread : Boolean;
begin

  Handle:=CreateToolHelp32SnapShot(TH32CS_SNAPTHREAD ,0);
  ThreadEntry.dwSize:=SizeOf(ThreadEntry);
  GotThread := Thread32First(Handle, ThreadEntry);

{$B-}
  if GotThread and (ThreadEntry.th32OwnerProcessID <> ProcessID) then
    repeat
     GotThread := Thread32Next(Handle,ThreadEntry);
    until (not GotThread) or (ThreadEntry.th32OwnerProcessID = ProcessID ) ;

{$B+}
    if GotThread
    then
      Result := ThreadEntry.th32ThreadID
    else Result := 0;
      CloseHandle(Handle);
end;
but how to get pid of last thread :(
madshi
Site Admin
Posts: 10749
Joined: Sun Mar 21, 2004 5:25 pm

Post by madshi »

I wouldn't know how to find out for sure which was the "last created thread" in a process. Of course you could try enumerating all threads and hope that the last one listed would also be the last one created. But I wouldn't bet on that it really is. I'm not even sure if Windows itself keeps a record of which thread was created at which time!
iconic
Site Admin
Posts: 1064
Joined: Wed Jun 08, 2005 5:08 am

Post by iconic »

You can't judge the "last created" thread by merely its thread id (TID), the only way that I know of is to compare thread creation times via GetThreadTimes(), it will fill a FILETIME struct with the creation time of the thread. Enumerate all threads in a process, like you're doing, and compare all thread creation times (param 2 of GetThreadTimes) while looking for the highest time, that will be your last created thread without a doubt in a given process.

--Iconic
Post Reply