c - 如何发送进程间消息?

标签 c winapi

PostMessageSendNotifyMessage 均失败,并显示 ERROR_MESSAGE_SYNC_ONLY。所以我剩下的唯一选择是 SendMessage 但它似乎没有做任何事情 - 它返回零,并且 GetLastErrorERROR_ENVVAR_NOT_FOUND

这是我的发件人代码(流程 1):

SendMessage(FindWindowEx(HWND_MESSAGE,NULL,"Message","serverwindow"),WM_COPYDATA,HWND_MESSAGE,
        &(COPYDATASTRUCT){0, sizeof "localhost", "localhost"})

接收者(进程0):

HWND hWnd=CreateWindowExA(0,"Message","serverwindow",0,0,0,0,0,HWND_MESSAGE,NULL,GetModuleHandle(NULL),NULL);
MSG msg;
while (Sleep(500), true)
while (PeekMessage(&msg,hWnd,0,0,PM_REMOVE))
    printf("message recieved\n");

最佳答案

正如 David 在评论中所述,WM_COPYDATA 是一条已发送消息,它不是一条排队消息,因此像您一样的消息循环已显示永远不会看到 (Get|Peek)Message() 输出的消息。消息直接传递到接收窗口的 WindowProc,因此需要在此处进行处理。但是,当跨线程/进程边界发送消息时,接收线程仍然需要运行消息循环,以便将已发送消息分派(dispatch)到该线程的窗口,而 (Get|Peek )Message() 正在等待排队消息。

根据 SendMessage()文档:

Sends the specified message to a window or windows. The SendMessage function calls the window procedure for the specified window and does not return until the window procedure has processed the message.

...

If the specified window was created by the calling thread, the window procedure is called immediately as a subroutine. If the specified window was created by a different thread, the system switches to that thread and calls the appropriate window procedure. Messages sent between threads are processed only when the receiving thread executes message retrieval code. The sending thread is blocked until the receiving thread processes the message. However, the sending thread will process incoming nonqueued messages while waiting for its message to be processed. To prevent this, use SendMessageTimeout with SMTO_BLOCK set. For more information on nonqueued messages, see Nonqueued Messages.

关于c - 如何发送进程间消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55906806/

相关文章:

objective-c - 使按钮暂停并播放声音代码错误

c - 为什么不同的格式说明符会使用 printf 给出不同的输出?

c - 僵尸进程与孤儿进程

c++ - EnumProcessModules 在 32 位 win7 上失败并出现错误 299

winapi - CryptAcquireContext——未解析的外部

c++ - 除了 SetCursor 之外还有什么可以重置光标形状?

c - c中结构体中的指针

c - 局部静态变量存储在哪里?如果是数据段,为什么它的范围不是整个程序?

c++ - ImpersonateLoggedOnUser 失败的条件

C InternetGetConnectedState 循环