C 程序間通訊

2021-06-18 01:34:44 字數 2465 閱讀 4334

程序之間通訊的幾種方法:

在windows程式中,各個程序之間常常需要交換資料,進行資料通訊。常用的方法有

使用記憶體對映檔案

通過共享記憶體dll共享記憶體

使用sendmessage向另一程序傳送wm_copydata訊息

比起前兩種的複雜實現來,wm_copydata訊息無疑是一種經濟實惠的一中方法.(zt)

wm_copydata訊息的主要目的是允許在程序間傳遞唯讀資料。windows在通過wm_copydata訊息傳遞期間,不提供繼承同步方式。sdk文件推薦使用者使用sendmessage函式,接受方在資料拷貝完成前不返回,這樣傳送方就不可能刪除和修改資料:

這個函式的原型及其要用到的結構如下:

sendmessage(hwnd,wm_copydata,wparam,lparam);

其中,wm_copydata對應的十六進製制數為0x004a

wparam設定為包含資料的視窗的控制代碼。lparam指向乙個copydatastruct的結構:

typedef struct tagcopydatastructcopydatastruct;

該結構用來定義使用者資料。

具體過程如下:

首先,在傳送方,用findwindow找到接受方的控制代碼,然後向接受方傳送wm_copydata訊息.

接受方在defwndproc事件中,來處理這條訊息.由於中文編碼是兩個位元組,所以傳遞中文時候位元組長度要搞清楚.

using system;    

using system.collections.generic;

using system.componentmodel;

using system.data;

using system.drawing;

using system.linq;

using system.text;

using system.windows.forms;

using system.runtime.interopservices;

namespace client

private void frmclient_load(object sender, eventargs e)

[dllimport("user32.dll",entrypoint="sendmessage")]

private static extern int sendmessage(

int hwnd, // handle to destination window

int msg, // message

int wparam, // first message parameter

ref copydatastruct lparam // second message parameter

);

[dllimport("user32.dll",entrypoint="findwindow")]

private static extern int findwindow(string lpclassname,string

lpwindowname);

public struct copydatastruct

const int wm_copydata = 0x004a;

private void btnsend_click(object sender, eventargs e)

}

}

}

接收端**:

using system;    

using system.collections.generic;

using system.componentmodel;

using system.data;

using system.drawing;

using system.linq;

using system.text;

using system.windows.forms;

using system.runtime.interopservices;

namespace server

private void form1_load(object sender, eventargs e)

public struct copydatastruct

const int wm_copydata = 0x004a;

protected override void defwndproc(ref system.windows.forms.message m)

}

}

}

c 程序間通訊

一 程序間通訊的方式 程序間通訊的方式有很多,常用的有共享記憶體 記憶體對映檔案 共享記憶體dll 剪下板等 命名管道和匿名管道 傳送訊息等幾種方法來直接完成,另外還可以通過 socket 口 配置檔案和登錄檔 等來間接實現程序間資料通訊任務。以上這幾種方法各有優缺點,具體到在程序間進行大資料量資料...

C 實現程序間通訊

利用tcp ip 來實現,不過目前只能實現一對一你一句我一句的聊天。有兩個.c檔案,ser.c和cli.c redhat系統,需要的標頭檔案如下 include include include include include include include 伺服器int main 2 struct ...

C 程序間通訊(windows)

1,共享記憶體 2,管道 3,訊號量 程序1測試 如下 include include 1 共享記憶體 handle myhmutex handle myhevent bool sharedmemoryfun 2 命名管道 define my pipe name pipe mypipe bool p...