用sendmessage实现进程间通信。
实现方式是发送WM_COPYDATA消息。
发送程序:
LRESULT copyDataResult; //copyDataResult has value returned by other app CWnd *pOtherWnd = CWnd::FindWindow(NULL, "卡口图片管理"); CString strDataToSend = "0DAE12A3D8C9425DAAE25B3ECD16115A" ; if (pOtherWnd) { COPYDATASTRUCT cpd; cpd.dwData = 0; cpd.cbData = strDataToSend.GetLength()+sizeof(wchar_t); //data length cpd.lpData = (void*)strDataToSend.GetBuffer(cpd.cbData); //data buffer copyDataResult = pOtherWnd->SendMessage(WM_COPYDATA,(WPARAM)AfxGetApp()->m_pMainWnd->GetSafeHwnd(),(LPARAM)&cpd); strDataToSend.ReleaseBuffer(); } else { AfxMessageBox("Unable to find other app."); }
这里字符串长度为strDataToSend.GetLength()+sizeof(wchar_t),其中sizeof(wchar_t)指 \0 的长度。
接收程序:
接收程序先给窗口(我这里的窗口名叫“卡口图片管理”)添加WM_COPYDATA消息函数,然后在函数中添加成如下:
BOOL CCarRecogDlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct) { // TODO: 在此添加消息处理程序代码和/或调用默认值 CString strRecievedText = (LPCSTR) (pCopyDataStruct->lpData); string str(strRecievedText.GetBuffer(pCopyDataStruct->cbData)); //string str = strRecievedText.GetBuffer() ; printf("%s \n", str.c_str()) ; if (str == "0DAE12A3D8C9425DAAE25B3ECD16115A") { printf("正确接收 \n") ; } return CDialogEx::OnCopyData(pWnd, pCopyDataStruct); }
运行结果: