资源描述:
《进程间通信方式》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、一利用剪贴板进行进程间通信voidCClipboardDlg::OnBtnSend(){//TODO:Addyourcontrolnotificationhandlercodehereif(OpenClipboard()) //打开剪贴板{ EmptyClipboard(); //释放剪贴板中数据的句柄并分配剪贴板所有权给当前窗口 CStringstr; HANDLEhClip; char*pBuf; GetDlgItemText(IDC_EDIT_SEND,str); hClip=GlobalAlloc(GMEM_MOVEABLE,str.GetL
2、ength()+1); //从堆中分配指定字节的内存 pBuf=(char*)GlobalLock(hClip); //对全局内存对象加锁,并将句柄转换为指针 strcpy(pBuf,str); GlobalUnlock(hClip); //解锁 SetClipboardData(CF_TEXT,hClip); //以指定的格式在剪贴板上放置数据 CloseClipboard(); //关闭剪贴板}}voidCClipboardDlg::OnBtnRecv(){//TODO:Addyourcontrolnotificationhan
3、dlercodehereif(OpenClipboard()){ if(IsClipboardFormatAvailable(CF_TEXT)) //检测剪贴板是否包含指定格式的数据 { HANDLEhClip; hClip=GetClipboardData(CF_TEXT); //从剪贴板中获取指定格式的数据 char*pBuf; pBuf=(char*)GlobalLock(hClip); //将句柄转换为地址 GlobalUnlock(hClip); SetDlgItemText(IDC_EDIT_RECV,pBuf);
4、CloseClipboard(); }}}二利用匿名管道进行进程间通信(匿名管道只能在父子进程间通信)父进程voidCParentView::OnPipeCreate(){//TODO:AddyourcommandhandlercodehereSECURITY_ATTRIBUTESsa;sa.bInheritHandle=TRUE;sa.lpSecurityDescriptor=NULL;sa.nLength=sizeof(SECURITY_ATTRIBUTES);if(!CreatePipe(&hRead,&hWrite,&sa,0)) //创建一个匿名管道并返
5、回管道的读写句柄{ MessageBox("创建匿名管道失败!"); return;}STARTUPINFOsui;ZeroMemory(&sui,sizeof(STARTUPINFO));sui.cb=sizeof(STARTUPINFO);sui.dwFlags=STARTF_USESTDHANDLES;sui.hStdInput=hRead;sui.hStdOutput=hWrite;sui.hStdError=GetStdHandle(STD_ERROR_HANDLE);PROCESS_INFORMATIONpi;if(!CreateProcess("..
6、\Child\Debug\Child.exe",NULL,NULL,NULL, TRUE,0,NULL,NULL,&sui,&pi)){ CloseHandle(hRead); CloseHandle(hWrite); hRead=NULL; hWrite=NULL; MessageBox("创建子进程失败!"); return;}else{ CloseHandle(pi.hProcess); CloseHandle(pi.hThread);}}voidCParentView::OnPipeRead(){//TODO:Addyourcomman
7、dhandlercodeherecharbuf[100];DWORDdwRead;if(!ReadFile(hRead,buf,100,&dwRead,NULL)){ MessageBox("读取数据失败!"); return;}MessageBox(buf);}voidCParentView::OnPipeWrite(){//TODO:Addyourcommandhandlercodeherecharbuf[]="武汉科技大学黄家湖校区";DWORDdwWrite;if(!WriteFile(hWrite,buf,strlen(buf)+1,&