.NET - Find external applications main thread ID
-
22-08-2019 - |
Question
I'm trying to find the handle of the main thread of an external application. The program I am trying to find the main thread of is multithreaded and it is important I always find the main thread. I know that at most there will be one copy of this program running. This is how I am doing it at the moment:
Process[] someProcesses = Process.GetProcessesByName("some");
IntPtr threadHandle = OpenThread(ThreadAccess.SUSPEND_RESUME, false, (uint)someProcesses[0].Threads[0].Id);
Most of the time, Threads[0] is the main thread but other times it is not. How can I make sure that the thread that I find is the main thread of the other application?
Thankyou.
Solution
This is a wild guess, but via Processes
, you can get a ProcessThreadCollection
via the Threads
property. Each thread has a StartTime
(available as Ticks
as well), so assuming the main thread is the first to start, you could pick the one with the lowest start time.
Otherwise if you can get the call stack for each thread, you could look for the application entry point. I couldn't find a managed call for that, but I'm sure you can get it through P/Invoke.
OTHER TIPS
Talk about coming to the party late -- but if someone finds this in a Google search or something, what I do to ID my main thread is set Thread.CurrentThread.Name
to a value (like "Main") when my app starts up.