转载:https://www.cctry.com/thread-78882-1-1.html
发送方:
1 CString str="这是我要发送的给另外一个进程字符串。"; 2 COPYDATASTRUCT myCopyDATA; 3 myCopyDATA.cbData=str.GetLength(); 4 myCopyDATA.lpData=str.GetBuffer(0); 5 str.ReleaseBuffer(); 6 HWND hwnd=::FindWindow(NULL,"Receive"); //假设目标程序窗口标题为"Receive" 7 if (hwnd) 8 ::SendMessage(hwnd,WM_COPYDATA,NULL,(LPARAM)&myCopyDATA); 9 else 10 AfxMessageBox("目标程序没有运行。");
接收消息的程序(这里假设是基于对话框的工程)请按如下步骤来实现:
先给对话框类CReceiveDlg(如果你的接收程序为SDI工程的话,把CReceiveDlg类换成CMainFrame类)添加一个消息处理函数LRESULT OnReceive(WPARAM wParam,LPARAM lParam),代码如下:
1 LRESULT CReceiveDlg::OnReceive(WPARAM wParam,LPARAM lParam) 2 { 3 COPYDATASTRUCT *p = NULL ; 4 p = (COPYDATASTRUCT*)lParam; 5 CString strTemp; 6 memcpy(strTemp.GetBuffer((int)p->cbData),p->lpData,p->cbData); 7 strTemp.ReleaseBuffer(); 8 AfxMessageBox(strTemp); 9 return 0; 10 }
接着再给工程设定刚才添加的函数OnReceive为WM_COPYDATA消息的响应函数,在ReceiveDlg.cpp文件中如下地方加入一行代码:
1 BEGIN_MESSAGE_MAP(CReceiveDlg, CDialog) 2 //{{AFX_MSG_MAP(CReceiveDlg) 3 ON_WM_PAINT() 4 ON_WM_QUERYDRAGICON() 5 ON_MESSAGE(WM_COPYDATA,OnReceive) //只要添加这一行进行WM_COPYDATA消息映射 6 //}}AFX_MSG_MAP 7 END_MESSAGE_MAP()
好了,现在分别运行两个程序,应该可以在A程序中给B程序发送消息了,B收到消息后会弹出个MessageBox来显示从A程序发送来消息了。
注:
COPYDATASTRUCT *p = NULL ; p = (COPYDATASTRUCT*)lParam;
这里如果写成
COPYDATASTRUCT p = (COPYDATASTRUCT &)lParam;
编译时不会报错,但是得到的数据错误