// WM_COPYDATA 使用的结构
/*
* lParam of WM_COPYDATA message points to...
*/
typedef struct tagCOPYDATASTRUCT {
ULONG_PTR dwData;
DWORD cbData;
PVOID lpData;
} COPYDATASTRUCT, *PCOPYDATASTRUCT;
// 自己实现例子, 注意内存释放。
// EXE1
void CEXE1Dlg::OnBnClickedButton1()
{
COPYDATASTRUCT CDS;
char ch[256];
sprintf(ch, "ffffffuuuuuuu");
CWnd* pWnd = FindWindow(NULL,_T("EXE2"));
if(pWnd)
{
CDS.dwData = 0;
CDS.cbData = sizeof(ch);
CDS.lpData = ch;
::SendMessage(pWnd->m_hWnd, WM_COPYDATA,(WPARAM)0,(LPARAM)&CDS);
}
}
// EXE2
protected:
virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);
LRESULT CEXE2Dlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
// TODO: 在此添加专用代码和/或调用基类
if(message == WM_COPYDATA)
{
COPYDATASTRUCT* copyData = COPYDATASTRUCT*)lParam;
int nDataSize = copyData->cbData;
if(nDataSize > 0)
{
char* ch = new char[nDataSize];
memcpy(ch, copyData->lpData, nDataSize);
::MessageBoxA(m_hWnd, ch, ch, MB_OK);
delete [] ch;
}
}
return CDialog::WindowProc(message, wParam, lParam);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
// 网上例子
// Allow room for the terminating 0, hence the + 1
int DataSize = UserTextMemo->Text.Length() + 1;
// Copy data to a local buffer
char* Data = new char[DataSize];
memcpy(
Data,
UserTextMemo->Text.c_str(),
DataSize
);
COPYDATASTRUCT CopyData;
CopyData.dwData = 0;
CopyData.cbData = DataSize;
CopyData.lpData = Data;
SendMessage(
WindowHandle,
WM_COPYDATA,
reinterpret_cast <WPARAM> (Handle),
reinterpret_cast <LPARAM> (&CopyData)
);
delete [] Data;
======================================================================
// Message.LParam is a pointer to the COPYDATASTRUCT,
// so we will cast it to a local pointer
COPYDATASTRUCT* CopyData = reinterpret_cast <COPYDATASTRUCT*>
(Message.LParam);
// There can be a 32 bit value in the dwData field
// and more data in the lpData field.
// The cbData field tells us the size of the
// data pointed to by lpData. For this example,
// we're assuming it's either dwData or lpData
int DataSize = CopyData->cbData;
if(DataSize > 0) {
// Make a local copy
char* Data = new char[DataSize];
memcpy(Data, CopyData->lpData, DataSize);
// Update text in Memo control
ReceiverMemo->Lines->Text = Data;
delete [] Data;
}
else { // We received a number in CopyData->dwData
int NumberFromExternalApplication = CopyData->dwData;
// Update text in Memo control
ReceiverMemo->Lines->Text = IntToStr(
NumberFromExternalApplication
);
}