用文件映射来实现进程通信

这方法相对于管道、邮槽等方法而言简单快速。再配合个窗口消息,或者开个线程用Event对象通知,就能实时发送了。。没什么技术含量。。


发送程序:

	UpdateData();
	const LPCSTR strName = "test111";
	const DWORD len = m_strSend.GetLength() + 1;


	CWnd *pWnd = CWnd::FindWindow("#32770","Get");
	if(pWnd == NULL) {
		AfxMessageBox("找不到窗口");
		return;
	}
	HANDLE hFile = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,len,strName);
	if(hFile == NULL) {
		AfxMessageBox("无法创建文件映射");
		return;
	}
	char *pBuf = (char*)MapViewOfFile(hFile,FILE_MAP_ALL_ACCESS,0,0,len);
	if(pBuf == NULL) {
		AfxMessageBox("无法获取映射内存");
		CloseHandle(hFile);
		return;
	}
	strcpy(pBuf,m_strSend);
	UnmapViewOfFile(pBuf);
	pWnd->SendMessage(WM_USER_REV,len,0);
	CloseHandle(hFile);


接受程序:

ON_MESSAGE(WM_USER_REV,OnRecv)


LRESULT CGetDlg::OnRecv(WPARAM len, LPARAM lParam)
{
	const LPCSTR strName = "test111";
	
	AfxMessageBox("收到消息,开始接受");
	HANDLE hFile = OpenFileMapping(FILE_MAP_ALL_ACCESS,FALSE,strName);
	if(hFile == NULL) {
		AfxMessageBox("无法打开文件映射");
		return 0;
	}
	char *pBuf = (char*)MapViewOfFile(hFile,FILE_MAP_ALL_ACCESS,0,0,len);
	if(pBuf == NULL) {
		AfxMessageBox("无法获取映射内存");
		CloseHandle(hFile);
		return 0;
	}
	MessageBox(pBuf);
	UnmapViewOfFile(pBuf);
	CloseHandle(hFile);
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值