关于PostThreadMessage能实现进程间通信吗?
看到网上有帖子说可以实现,证据:程序代码:
3.发送线程消息: 优点:简单,方便 缺点:能发送的数据太小 用到的函数: FindWindow //查找窗口 GetWindowThreadProcessId //获取指定窗口的进程ID和主线程ID PostThreadMessage//发送消息到指定线程 如果是向主线程发送消息,接收线程消息的进程,可以覆盖虚函数PreTranslateMessage来完成消息的处理 ProcessA: view sourceprint?01 //找窗口句柄 02 HWND hWnd = ::FindWindow(NULL, "ProcessB"); 03 if (hWnd == NULL) 04 { 05 return; 06 } 07 08 //主线程ID 09 DWORD dwThreadID = 0; 10 //获取指定窗口主线程ID, 第二个参数是进程ID out 传出值. 11 dwThreadID = ::GetWindowThreadProcessId(hWnd, NULL); 12 13 //向主线程发送线程消息 14 BOOL bRet = ::PostThreadMessage(dwThreadID, WM_USER + 2, 1, 2); 15 if (!bRet) 16 { 17 AfxMessageBox("发送线程消息失败!"); 18 } ProcessB: view sourceprint?01 BOOL CProcessBDlg::PreTranslateMessage(MSG* pMsg) 02 { 03 // TODO: Add your specialized code here and/or call the base class 04 if(pMsg->message == WM_USER + 2) 05 { 06 CString txt; 07 txt.Format("参数1:%d,参数2:%d", pMsg->wParam, pMsg->lParam); 08 AfxMessageBox(txt); 09 return TRUE; 10 } 11 12 return CDialog::PreTranslateMessage(pMsg); 13 }
但是按照这个思路,写了个简单的例子,发现并没有效果,特来咨询各位大鸟!!!
两个对话框:A,B,A包含一个EDIT跟BUTTON,B包含一个edit,点击A的button,把A中edit的内容发动到B的edit中,用的内存映射实现的,代码如下:
程序代码:
A: #define WM_MYMESSAGE WM_USER+1 case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_BUTTON1: GetDlgItemText(hwndDlg,IDC_EDIT1,szEditText,MAX_PATH); //用WM_COPYDATA消息实现 //MessageBox(hwndDlg,szEditText,TEXT("B"),MB_OK); /*hwndDestination=FindWindow(NULL,TEXT("IPC_B")); copydatastruct.dwData=NULL; copydatastruct.cbData=sizeof(szEditText); copydatastruct.lpData=szEditText; SendMessage(hwndDestination,WM_COPYDATA,(WPARAM)hwndDlg,(LPARAM)©datastruct);*/ //用内存映射实现如下 if(s_hFileMap!=NULL) { if(GetLastError()==ERROR_ALREADY_EXISTS) { MessageBox(hwndDlg,TEXT("映射对象已经存在!"),TEXT("出错"),MB_ICONINFORMATION); } else { pView=MapViewOfFile(s_hFileMap,FILE_MAP_READ|FILE_MAP_WRITE,0,0,0); if(pView!=NULL) { //pView=szEditText; lstrcpy((LPWSTR)pView,szEditText); UnmapViewOfFile(pView); hwndDestination=FindWindow(NULL,TEXT("IPC_B")); dwThreadID=GetWindowThreadProcessId(hwndDestination,NULL); bRet=PostThreadMessage(dwThreadID,WM_MYMESSAGE,0,0); bError=GetLastError(); //bRet=SendMessage(hwndDestination,WM_MYMESSAGE,0,0); if(!bRet) { MessageBox(hwndDlg,TEXT("发送消息失败!"),TEXT("错误"),MB_ICONINFORMATION); } } else { MessageBox(hwndDlg,TEXT("不能映射文件视图!"),TEXT("出错"),MB_ICONINFORMATION); } } } else { MessageBox(hwndDlg,TEXT("不能创建映射"),TEXT("出错"),MB_ICONINFORMATION); } return 0; default: break; } } return TRUE;B:
程序代码:
#define WM_MYMESSAGE WM_USER+1 case WM_MYMESSAGE: s_hFileMap=OpenFileMapping(FILE_MAP_READ|FILE_MAP_WRITE,0,TEXT("ShareData")); if(s_hFileMap!=NULL) { pView=MapViewOfFile(s_hFileMap,FILE_MAP_READ|FILE_MAP_WRITE,0,0,0); if(pView!=NULL) { SetDlgItemText(hwndDlg,IDC_EDIT1,(LPCWSTR)pView); UnmapViewOfFile(pView); } else { MessageBox(hwndDlg,TEXT("不能映射文件视图!"),TEXT("出错"),MB_ICONINFORMATION); } } else { MessageBox(hwndDlg,TEXT("不能打开映射"),TEXT("出错"),MB_ICONINFORMATION); } break;
麻烦大家看看用postthreadmessage如何实现呢?谢谢先!