首页 > 代码库 > 获取窗口句柄,并向窗口发送自定义消息

获取窗口句柄,并向窗口发送自定义消息

转载自:http://www.cnblogs.com/pen-ink/articles/1815306.html#commentform

//①自定义消息
//两个进程中定义相同的消息
#define WM_COMM (WM_USER + 100)

//发送窗口发送按钮处理,自定义消息为WM_COMM,接收窗口为DataRecv
void CDataSendDlg::OnBnClickedOk()
{
// TODO: 在此添加控件通知处理程序代码
CWnd *pWnd = CWnd::FindWindow(NULL, _T("DataRecv"));
if(pWnd == NULL)
{
MessageBox(_T("Unable to find DataRecv."));
return;
}
pWnd->PostMessage(WM_COMM, NULL, NULL);
}
//接收窗口处理WM_COMM自定义消息
BEGIN_MESSAGE_MAP(CDataRecvDlg, CDialog)
ON_MESSAGE(WM_COMM, OnRecvMsg)
END_MESSAGE_MAP()

LRESULT CDataRecvDlg::OnRecvMsg(WPARAM, LPARAM)
{
MessageBox(_T("I Received Message!"));
return (LRESULT)0;
}
//②WM_COPYDATA消息,主要目的是允许在进程间传递只读数据(COPYDATASTRUCT结构封装),用SendMessage()发送
//发送窗口发送只读数据
void CDataSendDlg::OnBnClickedOk()
{
// TODO: 在此添加控件通知处理程序代码
CString str;
GetDlgItemText(IDC_EDIT2,str);
CWnd *pWnd = CWnd::FindWindow(NULL, _T("DataRecv"));
if(pWnd == NULL)
{
MessageBox(_T("Unable to find DataRecv."));
return;
}
CString data;
GetDlgItemText(IDC_EDIT2, data);
COPYDATASTRUCT cpd = {0};
cpd.cbData = http://www.mamicode.com/(data.GetLength() + 1) * 2;
cpd.lpData = http://www.mamicode.com/(PVOID)data.GetString();
pWnd->SendMessage(WM_COPYDATA, 0, (LPARAM)&cpd);
}
//接收窗口接收只读数据
BOOL CDataRecvDlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
CString str;
str = (LPCWSTR)pCopyDataStruct->lpData;
str = str.Left(pCopyDataStruct->cbData);
SetDlgItemText(IDC_EDIT1, str);
return CDialog::OnCopyData(pWnd, pCopyDataStruct);
}

// 发送WM_CLOSE 消息

void CSendMessageToWindowDlg::OnBnClickedButtonSendmessage()
{
// TODO: 在此添加控件通知处理程序代码
CWnd *pWnd = CWnd::FindWindow(NULL, _T("spyXX"));
if (pWnd == NULL)
{
MessageBox(_T("接收程序没有运行!"));
return;
}

pWnd->SendMessage(WM_CLOSE, NULL, 0);
}

获取窗口句柄,并向窗口发送自定义消息