Search code examples
c#.netsendmessageinter-process-communicat

How can I send a message to a specific process by process id rather than by window handle?


To work around the limitations of GenerateConsoleCtrlEvent, I have to create an intermediate "middle-man" process to handle launching some console applications. The process's main purpose is to call GenerateConsoleCtrlEvent on itself, causing itself and all child process to close cleanly in response to a ctrl+break signal (rather than using Process.Kill). This need arises from the fact that GenerateConsoelCtrlEvent basically has no effect unless the process group id is zero, which means it is only ever effective on the calling process group itself. See: https://stackoverflow.com/a/2431295/88409

So anyway... I've created this intermediate process, which starts a thread that calls Application.Run on a form which processes specific user-defined messages.

My problem is... how do send messages to this process to control it?

I have the Process object and its process id, but that's all. Process.MainWindowHandle is zero.

So I need a way to send a message to a specific process or broadcast the message to all windows in a specific process.

FindWindow is not an option, because it tries to identify a window by name and class on any process, which is unreliable. I want to send a message to a specific process with no ambiguity.


Solution

  • You can't send nor post a message to a process, but you can post a message to a thread. Of course, that thread must have started a message loop to process it.