Game Development Reference
After you have successfully sent the data, it is important that you free the memory
from Windows, because this memory is not managed by the .NET garbage collector.
Remember that receiving applications are not supposed to manipulate or free the
memory referenced by this pointer, so it is your responsibility to do so.
Perhaps the trickiest part about using WM_COPYDATA with a managed application is
that you cannot just tap into the message handler of a form. You need to create a
wrapper class that inherits from NativeWindow , and assign to NativeWindow the han-
dle of the form you are using. The following code shows the implementation of the
NativeWindow wrapper class. You will also notice that the pointer we received gets
Marshal ed back into a COPYDATASTRUCT instance.
public sealed class CopyDataWindow : NativeWindow, IDisposable
protected override void WndProc(ref System.Windows.Forms.Message message)
COPYDATASTRUCT copyData = Marshal.PtrToStructure(message.LParam,
if (copyData._dataSize > 0)
byte data = new byte[copyData._dataSize];
message.Result = (IntPtr)1;