Initial data: there is a WinAPI C ++ application (server). The application knows the Windows Form C # application process handle (client). The server creates the data and sends it to the client:

COPYDATASTRUCT cds; cds.dwData = 1; cds.lpData = "dddd"; cds.cbData = 4; PostMessage(hwnd/*повторюсь, дескриптор получателя известен*/, WM_COPYDATA, NULL, (LPARAM)&cds); 

Further, the client must accept them. I accept this:

 [StructLayout(LayoutKind.Sequential)] struct COPYDATASTRUCT { public IntPtr dwData; public int cbData; public IntPtr lpData; } private const int WM_COPYDATA = 0x004A; protected override void WndProc(ref Message m) { switch(m.Msg) { case WM_COPYDATA: { string message = ""; unsafe { COPYDATASTRUCT* cds = (COPYDATASTRUCT*)m.LParam; message = Marshal.PtrToStringAnsi(cds->lpData); } this.Log.Text += message; // Log - это richtextbox break; } } base.WndProc(ref m); } 

However, the client does not catch the message (changes in the richtextbox) is not fixed. What is the trouble? Thank. PS: looked in spy - the message does not come.

  • H'm, "dddd" is local data. You need a pointer to the data in the heap, no? Otherwise, another process runs the risk of garbage. - Alexander Petrov
  • @AlexanderPetrov: It seems that WM_COPYDATA should smarshallirovat. But only the code on the receiving side does not really like something for me. - VladD
  • And why Marshal.PtrToStringAnsi(cds->lpData); ? What do you have on the index? Look in the debugger. - VladD
  • one
    @Range: And the link says why PostMessage won't roll - VladD
  • one
    @Range: Glad to be able to help. I read myself to understand :) - VladD

1 answer 1

The WM_COPYDATA needs to be sent via SendMessage , not PostMessage . It cannot work with PostMessage , and the return value of PostMessage should tell you that sending has not occurred.

From win32.hlp (but for some reason this is not on MSDN):

An application must be SendMessage , not the PostMessage function.

It is not necessary to record the data.

The sending process must be changed.

The receiving application should consider the data read-only. During the processing of the message. Memory referenced by pcds. If you receive your local buffer.


Why it happens?

The fact is that your message will be smarshallirovano in another process. The window manager will need to know when the processing is finished in order to free his buffer that he used for marshalling. But for PostMessage sending is asynchronous, and the window manager does not know when the message will be processed and when it is possible to clean the memory.

Additional reading on the topic: Why I’m not a message, but I can send message time with a tiny timeout?