两个测试程序,都是MFC基于对话框的应用程序,一个是发送者,一个是接收者。
两个程序都使用同一个结构体:
typedef struct { char imsi[20]; char options[512]; }_tagResult;
按钮点击事件:
void CCardXSenderDlg::OnButton1() { HWND hwnd = ::FindWindow(NULL, "CardXApp"); if(hwnd) { static _tagResult result; static COPYDATASTRUCT sendData; ZeroMemory(&result, sizeof(_tagResult)); strcpy(result.imsi, "result_imsi0"); strcpy(result.options, "result_options0"); ZeroMemory(&sendData, sizeof(sendData)); sendData.lpData = &result; sendData.cbData = sizeof(result); ::SendMessage(hwnd, WM_COPYDATA, NULL, (LPARAM)&sendData); // ::PostMessage(hwnd, WM_COPYDATA, NULL, (LPARAM)&sendData); // can't use ::PostMessage() } }
BOOL CCardXAppDlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct) { CString msg; _tagResult result; memcpy(&result, pCopyDataStruct->lpData, sizeof(result)); msg.Format("imsi=[%s], options=[%s]", result.imsi, result.options); MessageBox(msg); return CDialog::OnCopyData(pWnd, pCopyDataStruct); }
注意:发送WM_COPYDATA消息时,必须使用SendMessage,不能使用PostMessage,否则接收端会收不到消息的。