使用WM_COPYDATA实现跨进程通讯(上)

1、发送方MFC

void XXX::SendCopyDataMessage(CString strWinTitle, CString strMsg)
{
	HWND hdlg;
	hdlg = ::FindWindow(NULL, strWinTitle);
	if (NULL != hdlg)
	{
		COPYDATASTRUCT cds = { 0 };
		cds.dwData = 0;
		cds.cbData = (strMsg.GetLength()+1)*sizeof(TCHAR);
		cds.lpData = strMsg.GetBuffer(strMsg.GetLength());
		::SendMessage(hdlg, WM_COPYDATA, (WPARAM)this->m_hWnd, (LPARAM)&cds);
		strMsg.ReleaseBuffer();
	}
}

2、接收方MFC

BOOL XXX::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct)
{
	CString strMsg;
	if (pCopyDataStruct && pCopyDataStruct->cbData)
	{
		strMsg = (LPCTSTR)(pCopyDataStruct->lpData);
		MessageBox(strMsg, L"WM_COPYDATA",  MB_OK);
	}

	return CDialogEx::OnCopyData(pWnd, pCopyDataStruct);
}

Comments are closed.