views:

363

answers:

1

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.

+2  A: 

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.

Brian Rasmussen