使用SendMessage WM_COPYDATA发送双数组

时间:2013-12-13 17:56:14

标签: c# sendmessage wm-copydata

我有问题从一个应用程序发送一个双数组到另一个应用程序(都是c#)。

我尝试格式化CopyData Struct,如下所示:

    [StructLayout(LayoutKind.Sequential)]
    public struct CopyDataStruct
    {
        public IntPtr dwData;
        public int cbData;
        [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.R8)]
        public double[] lpData;
    }

Sender Application我填充结构如下:

            double[] a = new double[2] { 1.0, 2.0 };
            int size = Marshal.SizeOf(typeof(double)) * a.Count();

            CopyDataStruct copyDataStruct;
            copyDataStruct.dwData = IntPtr.Zero;
            copyDataStruct.lpData = a;
            copyDataStruct.cbData = size;

            int result = SendMessage(hWnd, WM_COPYDATA, 0, ref copyDataStruct);

Receiver Application中,我试试这个:

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        switch (msg)
        {
            case (int)WINMESSAGES.WM_COPYDATA:
                CopyDataStruct cp = (CopyDataStruct)Marshal.PtrToStructure(lParam, typeof(CopyDataStruct));

                break;
        }

        return IntPtr.Zero;
    }

但在cp.lpDat中,值为null。我不知道我发错了还是收错了。请帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

您需要使用本机内存。传递C#double[]就好了。它将被垃圾收集(哎呀,它甚至没有在C#中分配 - 它只是在堆栈中)。您可以使用不安全/固定关键字固定对象,也可以使用AllocHGlobal

这是我从互联网上扯下的一些代码。演示发送部分:

    // Marshal the managed struct to a native block of memory.
    var myStruct = new double[2] { 1.0, 2.0 };
    int myStructSize = Marshal.SizeOf(myStruct); 
    IntPtr pMyStruct = Marshal.AllocHGlobal(myStructSize);
    try
    {
        Marshal.StructureToPtr(myStruct, pMyStruct, true);

        COPYDATASTRUCT cds = new COPYDATASTRUCT();
        cds.cbData = myStructSize;
        cds.lpData = pMyStruct;

        // Send the COPYDATASTRUCT struct through the WM_COPYDATA message to 
        // the receiving window. (The application must use SendMessage, 
        // instead of PostMessage to send WM_COPYDATA because the receiving 
        // application must accept while it is guaranteed to be valid.)
        NativeMethod.SendMessage(hTargetWnd, WM_COPYDATA, this.Handle, ref cds);

        int result = Marshal.GetLastWin32Error();
        if (result != 0)
        {
            MessageBox.Show(String.Format(
                "SendMessage(WM_COPYDATA) failed w/err 0x{0:X}", result));
        }
    }
    finally
    {
        Marshal.FreeHGlobal(pMyStruct);
    }

采取:http://code.msdn.microsoft.com/windowsdesktop/CSReceiveWMCOPYDATA-dbbc7ed7