views:

50

answers:

1

Hi,

I'm creating a process from .NET using Process.Start. The new process is a legacy app, written in C/C++. To communicate with it, I need to do the equivalent of PostThreadMessage to its primary thread.

I'd be happy to use P/Invoke to call PostThreadMessage, but I can't see how to find the primary thread. The Process object has a collection of threads, but the doc says the first item in the collection need not be the primary thread. The Thread objects themselves don't seem to have any indication of whether they're primary. And while I could look at the thread collection immediately after creating the process, that's no guarantee there would be only one.

So, is there a way for me to determine another process' primary thread from .NET, or do I need to resort to using Win32's CreateProcess?

Thanks,

Bob

A: 

If the process has a window, you can use the GetWindowThreadProcessId API to get the GUI thread, which usually is the primary thread (use Process.MainWindowHandle to get the window handle).

Another option would be to enumerate the threads (Process.Threads) and pick the first one that was started, based on the StartTime:

Process process = Process.Start(...);
process.WaitForInputIdle();
ProcessThread primaryThread = process.Threads.OrderBy(t => t.StartTime).First();

But it's probably not a very accurate technique...

Thomas Levesque
Unfortunately, the legacy app doesn't have a window. And if a process starts multiple threads quickly, their start times might be the same.
Bob A.