windows进程通信 -- WM_COPYDATA消息
WM_COPYDATA消息,在win32中用來(lái)進(jìn)行進(jìn)程間的數(shù)據(jù)傳輸。
typedef struct tagCOPYDATASTRUCT { // cds DWORD dwData; DWORD cbData; PVOID lpData; } COPYDATASTRUCT;其中dwData為32位的自定義數(shù)據(jù), lpData為指向數(shù)據(jù)的指針,cbData為lpData指針指向數(shù)據(jù)的大小(字節(jié)數(shù))。
一般推薦用SendMessage函數(shù)進(jìn)行發(fā)送,這樣就能確保在接收方復(fù)制數(shù)據(jù)前避免發(fā)送方能修改或刪除數(shù)據(jù);
LRESULT SendMessage(HWND hWnd, // handle of destination windowUINT Msg, // message to sendWPARAM wParam, // first message parameterLPARAM lParam // second message parameter );這里:
hWnd:為接收進(jìn)程的窗體句柄;
Msg:WM_COPYDATA;
wParam:為發(fā)送進(jìn)程的窗體句柄;
lParam:為指向COPYDATASTRUCT數(shù)據(jù)結(jié)構(gòu)的指針;
這里需要注意的:傳輸?shù)腃OPYDATA數(shù)據(jù)在發(fā)送后要避免被發(fā)送進(jìn)程中的其他線程修改,其次要確保被傳輸?shù)臄?shù)據(jù)中沒(méi)有包含接收進(jìn)程無(wú)法訪問(wèn)的對(duì)象的指針或引用。比如:發(fā)送進(jìn)程自身的HDC、HBITMAP之類的東西,它們對(duì)于接收進(jìn)程來(lái)說(shuō)是無(wú)效的。另外,接收進(jìn)程窗體句柄可以通過(guò)FindWindow函數(shù)獲取:
const char szDlgTitle[] = "ReceiveProcess"; HWND hRecvWindow = ::FindWindow(NULL, szDlgTitle);這里的“ReceiveProcess”為接收進(jìn)程的名字;
同時(shí),接收數(shù)據(jù)的進(jìn)程中,首先在消息映射表中增加WM_COPYDATA消息映射,然后定義消息映射函數(shù),其函數(shù)的格式為:
BOOL CCanCollectorDlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct) {.... }主要代碼如下:(這里發(fā)送進(jìn)程發(fā)送當(dāng)前的時(shí)間給接收進(jìn)程)
發(fā)送進(jìn)程:
void CProcessCommDlg::OnBTNStart1() {const char szDlgTitle[] = "ReceiveProcess"; HWND hSendWindow =this->GetSafeHwnd();HWND hRecvWindow = ::FindWindow(NULL, szDlgTitle); COPYDATASTRUCT CopyData; char szSendBuf[100]; time_t timenow; time(&timenow); sprintf(szSendBuf, "%s", ctime(&timenow));//注意,ctime()返回的字符串后面帶了'\n' CopyData.dwData = 0; CopyData.cbData = strlen(szSendBuf); szSendBuf[CopyData.cbData - 1] = '\0'; CopyData.lpData = szSendBuf; ::SendMessage(hRecvWindow, WM_COPYDATA, (WPARAM)hSendWindow, (LPARAM)&CopyData); printf("%s\n", szSendBuf); }接收進(jìn)程:
BEGIN_MESSAGE_MAP(CCanCollectorDlg, CDialog)//{{AFX_MSG_MAP(CCanCollectorDlg) ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_WM_COPYDATA()//}}AFX_MSG_MAP END_MESSAGE_MAP()........BOOL CCanCollectorDlg::OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct) {char szBuffer[300]; memset(szBuffer, 0, sizeof(szBuffer)); sprintf(szBuffer, "dwData:%d cbData:%d\r\nlpData:0x%08x = %s\r\n\r\n", pCopyDataStruct->dwData, pCopyDataStruct->cbData, (PVOID)pCopyDataStruct->lpData, (char*)pCopyDataStruct->lpData); return CDialog::OnCopyData(pWnd, pCopyDataStruct); }轉(zhuǎn)載于:https://www.cnblogs.com/xiekeli/p/3994380.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的windows进程通信 -- WM_COPYDATA消息的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 课程上线 -“新手入门 : Window
- 下一篇: 图解面向对象中的聚合与耦合概念