4

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

Bob A.
  • 41
  • 1

2 Answers2

0

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
  • 286,951
  • 70
  • 623
  • 758
  • 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. Oct 08 '10 at 12:45
0

You don't need a Window to use thread message queues. Thread message queues are created as soon as the thread calls user functions like GetMessage or PeekMessage.

see more info here at: About Messages and Message Queues

Still you will need to determine the "primary" thread Id (and the posting thread/process will need sufficient rights as well) by some mean.

There is an answer here: http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/42de8f6a-61f4-495e-a69d-bd018e07c6f7

(see the "nobugz" answer)

Simon Mourier
  • 132,049
  • 21
  • 248
  • 298