I have codes written in native C++ that controls other processes (“client processes”) created by CreatePrcess() and other Windows APIs
Then client processes (console, single-thread) wait for the message MSG_OK from the “server” process and resume running when the message is received.
I used PostThreadMessage() and it worked fine.
int MSG_OK = RegisterWindowMessage("MSG_OK");
void run(TCHAR* path) {
STARTUPINFO si={0,}; si.cb=sizeof(STARTUPINFO); si.dwFlags=0;
PROCESS_INFORMATION pi;
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
Sleep(1000); // Just for simplicity. Actual code is message-based
PostThreadMessage(pi.dwThreadId, MSG_OK, 0, 0);
CloseHandle(pi.hProcess); // closing process handle makes usage count 1
CloseHandle(pi.hThread);
}
Now I’d like to rewrite the code in C#, using p/invoke’s as little as possible.
The following is the code I’m working on:
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
public static extern bool PostThreadMessage(uint threadId, int msg, IntPtr wParam, IntPtr lParam);
public void run(string path) {
Process proc = new Process();
ProcessStartInfo si = new ProcessStartInfo();
si.FileName = path;
proc.StartInfo = si;
proc.Start();
uint threadId; // <----?
PostThreadMessage(threadId, MSG_OK, 0, 0);
proc.Dispose();
}
I found C# classes such as Process and ProcessStartinfo but couldn’t find any member similar to dwThreadId. Is there any?
EDIT: Since the client process is a single thread app,
proc.Threads[0].id
seems to be the threadId I’m looking for. Am I doing something wrong?
Please see this thread.
I would consider using some other approaches like mutexes, events or semaphores.