C# 等效于另一个进程的postthreadmessage

标签 c# c++ interop pinvoke ipc

我有用 native C++ 编写的代码,用于控制由 CreatePrcess() 和其他 Windows API 创建的其他进程(“客户端进程”)
然后客户端进程(控制台,单线程)等待来自“服务器”进程的消息 MSG_OK 并在收到消息时恢复运行。
我使用了 PostThreadMessage(),它运行良好。

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);    
}

现在我想用 C# 重写代码,尽可能少地使用 p/invoke。 以下是我正在处理的代码:

[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();
}

我找到了 C# 类,例如 Process 和 ProcessStartinfo,但找不到任何类似于 dwThreadId 的成员。有吗?

编辑:由于客户端进程是单线程应用程序,

 proc.Threads[0].id

似乎是我要找的threadId。我做错了什么吗?

最佳答案

请参阅this thread .

我会考虑使用其他一些方法,例如 mutexes, events or semaphores .

关于C# 等效于另一个进程的postthreadmessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13810437/

相关文章:

c# - 陷入 C# 序列化困境

c++ - C++ 中的 PlaySound() 不起作用

C# .net Excel Interop 使 Excel 进程挂起

java - Clojure java interop - 调用重载(静态)方法

.net - 从 .NET 为非原始数据类型调用旧的 C++ 函数

c# - 如果图像丢失则加载默认图像

c#-excel interop - 在工作簿上创建图表而不是在工作表中

c# - 如何查看一个类型是否实现了一个接口(interface)?

c++ - 更简单的方法来写这个 if 函数 c++

c++ - 模仿 "if constexpr"行为,不可能?