PV(浏览量)
UV(访客数)
IP数

C#与C++通信

C#与C++相互发送消息

C#端:

namespace CshapMessage
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        IntPtr hwnd;

        const int WM_COPYDATA = 0x004A;

        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }

        [DllImport("User32.dll")]
        public static extern int SendMessage(int hwnd, int msg, int wParam, ref COPYDATASTRUCT IParam);
        [DllImport("User32.dll")]
        public static extern int FindWindow(string lpClassName, string lpWindowName);

        public MainWindow()
        {
            InitializeComponent();
            this.Title = "CshapMessage";
            this.Loaded += MainWindow_Loaded;
            this.Closed += MainWindow_Closed;
        }

        private void MainWindow_Closed(object sender, EventArgs e)
        {
            try
            {
                HwndSource.FromHwnd(hwnd).RemoveHook(WndProc);
            }
            catch (Exception) { }
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            hwnd = new WindowInteropHelper(this).Handle;
            HwndSource.FromHwnd(hwnd).AddHook(new HwndSourceHook(WndProc));
        }

        /// <summary>
        /// 向C++程序 CshapMessage发送消息
        /// </summary>
        /// <param name="nMessgeId"></param>
        /// <param name="strSend"></param>
        /// <returns></returns>
        private bool CshapSendMessage(int nMessgeId, String strSend)
        {
            int WINDOW_HANDLE = FindWindow(null, "VcMessage");//VcMessage为向C++程序发送的窗口名称
            if (WINDOW_HANDLE != 0)
            {
                COPYDATASTRUCT cdata;
                cdata.dwData = (IntPtr)100;//这里可以传入一些自定义的数据,但只能是4字节整数 
                cdata.lpData = strSend;//消息字符串
                cdata.cData = System.Text.Encoding.Default.GetBytes(strSend).Length+1;//注意,这里的长度是按字节来算的

                SendMessage(WINDOW_HANDLE, WM_COPYDATA, 0, ref cdata);
            }
            else
            {
                return false;
            }
            return true;
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            String strSend = "C#发送的信息";
            int nMessageId = 100;

            if (CshapSendMessage(nMessageId,strSend))
            {
                MessageBox.Show("发送消息成功");
            }
            else
            {
                MessageBox.Show("消息发送失败,请打开VcMessage程序");
            }
        }

        //接收消息。
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == WM_COPYDATA)
            {
                COPYDATASTRUCT cdata = new COPYDATASTRUCT();
                Type mytype = cdata.GetType();
                cdata = (COPYDATASTRUCT)Marshal.PtrToStructure(lParam, mytype);
                switch (cdata.dwData.ToInt32())
                {
                    case 1:
                        {
                            string strRecv = cdata.lpData;
                            break;
                        }
                    default:
                        break;
                }
            }

            return IntPtr.Zero;
        }
    }
}

C++端:

BOOL CVcMessageDlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值

	//接收C#发送来的数据
	switch (pCopyDataStruct->dwData)
	{
	case 100:
	{
		CStringA strRecv = (char*)pCopyDataStruct->lpData;
		break;
	}

	default:
	{
		break;
	}
	}

	return CDialogEx::OnCopyData(pWnd, pCopyDataStruct);
}

void CVcMessageDlg::OnBnClickedButton1()
{
	// TODO: 在此添加控件通知处理程序代码

	CStringA strSend = "VC发送的数据";

	if (VCSendMessage(1,strSend))
	{
		AfxMessageBox(_T("消息发送成功"));
	} 
	else
	{
		AfxMessageBox(_T("消息发送失败"));
	}
}

//************************************
// Method:    VCSendMessage
// FullName:  CVcMessageDlg::VCSendMessage
// Access:    public 
// Returns:   BOOL
// Qualifier: 向C#程序 CshapMessage发送消息
// Parameter: int nMessgeId
// Parameter: CStringA strSend
//************************************
BOOL CVcMessageDlg::VCSendMessage(int nMessgeId,CStringA strSend)
{
	HWND hSendWindow = this->m_hWnd;
	if (hSendWindow == NULL)
	{
		return FALSE;
	}
	
	CWnd *phwnd = FindWindow(NULL, _T("CshapMessage"));
	HWND hRecvWindow = NULL;
	if (phwnd == NULL)
	{
		return FALSE;
	}

	hRecvWindow = phwnd->GetSafeHwnd();

	if (hRecvWindow == NULL)
	{
		return FALSE;
	}

	COPYDATASTRUCT CopyData;
	CopyData.dwData = nMessgeId;
	CopyData.cbData = strSend.GetLength()+1;
	CopyData.lpData = (PVOID)strSend.GetBuffer(CopyData.cbData);

	::SendMessage(hRecvWindow, WM_COPYDATA, (WPARAM)hSendWindow, (LPARAM)&CopyData);

	return TRUE;
}

posted on 2016-12-30 17:02  赤龙绕月  阅读(925)  评论(2编辑  收藏  举报