用sendmessage實現進程間通訊。app
實現方式是發送WM_COPYDATA消息。函數
發送程序:spa
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 的長度。指針
接收程序:code
接收程序先給窗口(我這裏的窗口名叫「卡口圖片管理」)添加WM_COPYDATA消息函數,而後在函數中添加成以下:blog
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); }
運行結果:進程
win32程序和x64程序的指針長度是不同的。經大神指點,結構體中的成員變量只能是基本數據類型,不能是像string這樣的類,大致緣由是類中有函數,函數也是一個地址(說法貌似不嚴謹,大概是這個意思)。圖片
下面在以前的基礎上實現傳遞結構體。ci
結構體定義:字符串
struct NOTIFY_INFO_t { char GUID[1024]; char task_id[1024]; int index ; };
收發程序中的結構體定義要一致(結構體名能夠不一致,但內部須要一致)。
主要的注意點是結構體成員變量的定義,具體的收發其實差很少。
發送:
void CMFCApplication1Dlg::OnBnClickedButtonSend() { // TODO: 在此添加控件通知處理程序代碼 LRESULT copyDataResult; //copyDataResult has value returned by other app CWnd *pOtherWnd = CWnd::FindWindow(NULL, "卡口圖片管理"); CString strDataToSend = "0DAE12A3D8C9425DAAE25B3ECD16115A" ; if (pOtherWnd) { NOTIFY_INFO_t *pNotify = new NOTIFY_INFO_t(); memcpy(pNotify->GUID,"0DAE12A3D8C9425DAAE25B3ECD16115A",sizeof("0DAE12A3D8C9425DAAE25B3ECD16115A")) ; COPYDATASTRUCT cpd; cpd.dwData = 0; cpd.cbData = sizeof(NOTIFY_INFO_t); //data length cpd.lpData = (void*)pNotify; //data buffer copyDataResult = pOtherWnd->SendMessage(WM_COPYDATA,(WPARAM)AfxGetApp()->m_pMainWnd->GetSafeHwnd(),(LPARAM)&cpd); strDataToSend.ReleaseBuffer(); } else { AfxMessageBox("Unable to find other app."); } }
接收:
BOOL CCarRecogDlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct) { // TODO: 在此添加消息處理程序代碼和/或調用默認值 NOTIFY_INFO_t *pNotify ; pNotify = (NOTIFY_INFO_t *)pCopyDataStruct->lpData ; printf("%s \n",pNotify->GUID) ; return CDialogEx::OnCopyData(pWnd, pCopyDataStruct); }
運行結果: