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

这方法相对于管道、邮槽等方法而言简单快速。再配合个窗口消息,或者开个线程用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;
}


你可能感兴趣的:(研究)