1、使用 WM_COPYDATA 消息
发送数据的一方:(获得句柄的方法,最简单的方法就是使用FindWindow,找窗口类,或者名,如果你觉得这样不把握,那就利用SetProp个窗口做个记号....见文章“使用信号量找到窗口句柄”)
CString strWindowTitle = _T("ClientDemo"); CString strDataToSend = _T("Hello, Everyone fsdfsdfsdfdsfds,this is a test demo!"); HWND hOtherWnd = ::FindWindow(NULL, strWindowTitle.GetBuffer(0)); if (hOtherWnd != NULL && ::IsWindow(hOtherWnd)) { COPYDATASTRUCT cpd; cpd.dwData = 0; cpd.cbData = strDataToSend.GetLength() * sizeof(TCHAR); cpd.lpData = (void*)strDataToSend.GetBuffer(0); HRESULT hResult = ::SendMessage(hOtherWnd, WM_COPYDATA, (WPARAM)(AfxGetApp()->m_pMainWnd), (LPARAM)&cpd); strDataToSend.ReleaseBuffer(); }
ON_WM_COPYDATA()
afx_msg BOOL OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct);
BOOL CClientDemoDlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct) { if (pCopyDataStruct != NULL) { LPCTSTR pszText = (LPCTSTR)(pCopyDataStruct->lpData); DWORD dwLength = (DWORD)(pCopyDataStruct->cbData); TCHAR szRecvText[1024] = {0}; memcpy(szRecvText, pszText, dwLength); MessageBox(szRecvText, _T("Test"), MB_OK); } return CDialog::OnCopyData(pWnd, pCopyDataStruct); }
发送方:
CString str = _T( "Hello" ); HWND hWndReceived = FindWindow( "Receiver", NULL ); SendMessage( hWndReceived, WM_SETTEXT, 0, (LPARAM) str );
ON_MESSAGE( WM_SETTEXT, OnSetTextMsg )
afx_msg void OnSetTextMsg( WPARAM wParam, LPARAM lParam) OnSetTextMsg( WPARAM wParam, LPARAM lParam ) { char str[ 256 ]; wsprintf( str, "%s", (char*) lParam );MessageBox(str, _T("Test"), MB_OK);}
3、其他方法,如:
使用内存映射文件
通过共享内存DLL共享内存
进程间发送的内存需为完整的内存,不能在结构体中套结构体,不能让指针等于不完整的内存
COPYDATASTRUCT* pCpd = new COPYDATASTRUCT; pCpd->dwData = 1; pCpd->cbData = sizeof(int) + mBackupDataPath.GetLength()*sizeof(TCHAR); pCpd->lpData = new BYTE[pCpd->cbData]; *((int*)pCpd->lpData) = 1; //设置备份路径 1 memcpy((LPVOID)((int*)pCpd->lpData + 1), mBackupDataPath.GetBuffer(0), mBackupDataPath.GetLength()*sizeof(TCHAR)); ::SendMessage(callInstanceHwnd, WM_COPYDATA, NULL,(LPARAM)pCpd); mBackupDataPath.ReleaseBuffer(); delete pCpd->lpData; delete pCpd;