Question : Passing a string using SendMessage

I want to send a String from one Application to another. I'm using SendMessage to do this and am passing the string in the wParam. But for some reason, I'm not able to "get" that string in the receiving application. Any clues guys ?
I have registered a window message say APP_MY_MSG. Then I'm doing a

CString csUser = "User1";
lRet = ::SendMessage((HWND)-1, APP_MY_MSG, (WPARAM)csUserID, APP_ISUSERVALID);

In my other Application, I get the message fine and can even switch with the lParam (as APP_ISUSERVALID), but I'm not able to get the value that I pass from here. Cd u tell me whatzz wrong

Answer : Passing a string using SendMessage

There is some more information at:

http://msdn.microsoft.com/library/psdk/winbase/ipc_2mw1.htm

See where it says:

"The receiving application should consider the data read-only. The lParam parameter is valid only during the processing of the message. The receiving application should not free the memory referenced by lParam. If the receiving application must access the data after SendMessage returns, it must copy the data into a local buffer."

I think this is the heart of the matter.  I changed my code to that shown below.  It may be overly conservative but I'm not sure I know EXACTLY when Windows grabs the data out of mSendData.  If it's AFTER the function has returned the data may be gone or damaged.

The following seems to work reliably on Win98 and Win2000.  No NT4 system handy....

BOOL CCopyDataTestDlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct)
{
     // TODO: Add your message handler code here and/or call default
     ::Beep(500, 500);

     TCHAR *pRcvData = _tcsdup((TCHAR *)(pCopyDataStruct->lpData));

     SetDlgItemText(IDC_RCVDATA, pRcvData);

     free (pRcvData);

     return TRUE;

     //return CDialog::OnCopyData(pWnd, pCopyDataStruct);
}

void CCopyDataTestDlg::OnSendbutton()
{
     // TODO: Add your control notification handler code here
     static COPYDATASTRUCT cd;
     static CString mSendData;

     GetDlgItemText(IDC_SENDDATA, mSendData);
     
     cd.cbData = mSendData.GetLength() + 1;
     cd.dwData = 0;
     cd.lpData = (LPVOID)((LPCTSTR)mSendData);

     ::SendMessage(HWND_BROADCAST, WM_COPYDATA, (WPARAM)this->m_hWnd, (LPARAM)&cd);
}
Random Solutions  
 
programming4us programming4us