我正在用Visual Studio 2010开发4个应用程序(使用Internet中的已建立示例):C++ MFC中的2个应用程序(名为:SenderCpp和ReceiverCpp)和C#中2个的应用程序(命名为:SenderCsh和ReceiverCsh)来测试WM_DATACOPY进程间通信。

我的目标是让C++应用程序“SenderCpp”将一些数据发送到C#应用程序“ReceiverCsh”,但它不起作用,“ReceiverCsh”不会接收到任何消息。

所以:

  • SenderCpp-> ReceiverCpp:作品
  • SenderCsh-> ReceiverCsh:作品
  • SenderCpp-> ReceiverCsh:不起作用

  • SenderCpp代码为:
    void SendCopyData(HWND hFind)
    {
        COPYDATASTRUCT cp;
        StackRecord record;
    
        record.CursorX = 1;
        record.CursorY = -1;
    
       _tcscpy(record.cmdline, L"Hello World!");
       cp.cbData = sizeof(record);
       cp.lpData = &record;
       cp.dwData = 12;
       SendMessage(hFind, WM_COPYDATA, NULL, (LPARAM)&cp);
    }
    
    void CCANDriverDlg::OnBnClickedButton2()
    {
       HWND hWnd = ::FindWindow(NULL, CString("ReceiverCpp"));
       SendCopyData(hWnd);
    }
    
    void CCANDriverDlg::OnBnClickedButton1()
    {
       HWND hWnd = ::FindWindow(NULL, CString("ReceiverCsh"));
       SendCopyData(hWnd);
    }
    

    ReceiverCsh是:
     protected override void WndProc(ref Message m)
        {
            switch(m.Msg)
            {
                case WM_COPYDATA:
                    // Win32.CopyDataStruct st = (Win32.CopyDataStruct)Marshal.PtrToStructure(m.LParam, typeof(Win32.CopyDataStruct));
                    CopyDataStruct st = (CopyDataStruct)Marshal.PtrToStructure(m.LParam, typeof(CopyDataStruct));
                    //txtmessagereceive.Text = strData;
    
                    CANMessage MsgIn = new CANMessage(8);
                    MsgIn = (CANMessage)Marshal.PtrToStructure(st.lpData, typeof(CANMessage));
    
                    // Decode the marshaled message
                    txtmessagereceive.Text = "dwData = " + st.dwData.ToString() +"\r\n" +
                                            "cbData = " + st.cbData + " bytes\r\n" +
                                            "CANID = " + MsgIn.CANID.ToString() + "\r\n";
                    for (int i=0; i<8; i++)
                    {
                        txtmessagereceive.Text += String.Format("Data[{0}]={1}\r\n", i, MsgIn.Data[i]);
                    }
    
                    break;
                default:
                    // let the base class deal with it
                    base.WndProc(ref m);
                    break;
            }
        }
    

    使用Spy ++时,我看到监视“ReceiverCsh”时,SenderCpp发送WM_COPYDATA时未显示任何消息,而是分析了ReceiverCpp时显示了该消息。

    你有主意吗
    谢谢。

    最佳答案

    我想知道ReceiverCsh是否是控制台应用程序。为了使用WndProc覆盖,您需要一个消息泵来接收外部消息。确保是这种情况。

    有关更多详细信息,请参见Handling Messages in Console Apps

    关于c# - 从C++到C#的WM_COPYDATA,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14756299/

    10-09 05:45