An application must use theSendMessage function to send this message, not thePostMessage function. The data being passed must not contain pointers or other references to objects not accessible to the application receiving the data. While this message is being sent, the referenced data must not be changed by another thread of the sending process. The receiving application should consider the data read-only. The pcds parameter is valid only during the processing of the message. The receiving application should not free the memory referenced by pcds. If the receiving application must access the data after SendMessage returns, it must copy the data into a local buffer. MSDN好清楚的呀
得到窗口句柄:
SendMessage(WM_COPYDATA,dd,ee)
dd,ee为参数,具体内容收:ON_WM_COPYDATABOOL CMainFrame::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct)
{
......
return CMDIFrameWnd::OnCopyData(pWnd, pCopyDataStruct);
}
CString strDataToSend = _T("This is a message to send");
LRESULT copyDataResult;
CWnd *pOtherWnd = CWnd::FindWindow(NULL, strWindowTitle); if (pOtherWnd)
{
COPYDATASTRUCT cpd;
cpd.dwData = 0;
cpd.cbData = strDataToSend.GetLength();
cpd.lpData = (void*)strDataToSend.GetBuffer(cpd.cbData);
copyDataResult = pOtherWnd->SendMessage(WM_COPYDATA,
(WPARAM)AfxGetApp()->m_pMainWnd->GetSafeHwnd(),
(LPARAM)&cpd);
strDataToSend.ReleaseBuffer();
// copyDataResult has value returned by other app
}
else
{
AfxMessageBox("Unable to find other app.");
}
}接收端:
BEGIN_MESSAGE_MAP(CMyWnd, CWnd)
//{{AFX_MSG_MAP(CMyWnd)
...
ON_WM_COPYDATA()
...
//}}AFX_MSG_MAP
END_MESSAGE_MAP()...BOOL CMyWnd::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct)
{
CString strRecievedText = (LPCSTR) (pCopyDataStruct->lpData); AfxMessageBox(strRecievedText); return CMyWnd::OnCopyData(pWnd, pCopyDataStruct);
}
看了你的答复, 有个疑问。。不知道你试过没有。
既然WM_COPYDATA是这样子用的, 那不就和我们平时用其它消息一样, 为什么还要多加一层上去了。
例如 :SendMessage(hwnd, WM_COPYDATA, (WPARAM)hwnd, (LPARAM)&MY_OWN_STRUCT);
就是在MSDN里面关于COPYDATASTRUCT里面的两个成员
cbData
Specifies the size, in bytes, of the data pointed to by the lpData member.
lpData
Pointer to data to be passed to the receiving application. This member can be NULL. OK。。这里我用lpData来指向一个结构, cbData则指定结构的大小, 但如果这个结构里面还有
指针的话, 这个cbData的值应该怎么给了。
例如 :
struct MY_OWN_STRUCT
{
int iIndex;
char* pString;
}
struct MY_OWN_STRUCT
{
int iIndex;
char szString[MAX_CHARCOUNT];
}
The data being passed must not contain pointers or other references to objects not accessible to the application receiving the data.
2。根据常识判断:
WM_COPYDATA如果跨进程进行,那么操作系统会把lpData所指向的cbData个字节在目标进程的地址空间中做个备份,并将此备份的指针放入lpData,传给目标进程。如果一旦这其中的数据又包含了指针,操作系统肯定无法识别,也不会做出任何处理,所以在目标进程中肯定不能直接使用。
我在Mouse Hook 遇了点问题, 如果你们有空的话, 再去看看再帮一帮我。。http://www.csdn.net/expert/topic/214/214247.shtm
请大家帮忙De一下bug, 关于Mouse Hook的。(WIN32)
cpd.lpData 这个就是一个void*指针,指向你的&MY_OWN_STRUCT就可以了。更好的方法是两个进程注册一个消息,这样消息格式就可以自己定了。