利用WM_COPYDATA进行进程间通信

发信消息

void CControlDlg::OnBnClickedButtonSend()
{
    // TODO: 在此添加控件通知处理程序代码
    CString strWindowTitle =  _T("ClientDemo");  
    CString strDataToSend = _T("成功通信");  

    HWND hOtherWnd = ::FindWindow(NULL,_T("DLL窗口")); //_T("YK Application"),NULL
    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();  
    }  

}

DLL接收端先添加WM_COPYDATA中添加消息映射

BEGIN_MESSAGE_MAP(CWGDLG, CDialogEx)
    ON_WM_COPYDATA()//消息映射
    ON_BN_CLICKED(IDC_BUTTON1, &CWGDLG::OnBnClickedButton1)
    ON_BN_CLICKED(IDOK, &CWGDLG::OnBnClickedOk)
END_MESSAGE_MAP()

然后回函数中写代码

BOOL CWGDLG::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct)
{
    // TODO: 在此添加消息处理程序代码和/或调用默认值


    //AfxMessageBox((LPCSTR)(pCopyDataStruct->lpData));
    //MessageBox(NULL, _T("成功通信"), MB_OK);  

    if (pCopyDataStruct != NULL)  
    {  

        LPCTSTR pszText = (LPCTSTR)(pCopyDataStruct->lpData);  
        DWORD dwLength = (DWORD)(pCopyDataStruct->cbData);  
        TCHAR szRecvText[1024] = {0};  
        memcpy(szRecvText, pszText, dwLength);  
        MessageBox(szRecvText, _T("成功通信"), MB_OK);  
    }  
    return CDialogEx::OnCopyData(pWnd, pCopyDataStruct);
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。