其實(shí)對(duì)于兩個(gè)程序之間進(jìn)行通信的實(shí)現(xiàn)方式有很多種,一般會(huì)采用服務(wù)端+客戶(hù)端的模式,,此處我們是進(jìn)行兩個(gè)客戶(hù)端之間的通信,,如果用一種最簡(jiǎn)單的方式去實(shí)現(xiàn)的話(huà),我認(rèn)為可以采用寫(xiě)文件的方式,,即一個(gè)讀,一個(gè)寫(xiě)。這個(gè)寫(xiě)法的話(huà)可以參考之前的關(guān)于文件讀寫(xiě)的文章,; 但這里我們使用的是另一種,基于Windows API實(shí)現(xiàn)Windows消息的發(fā)送接收,; 實(shí)現(xiàn)功能: 開(kāi)發(fā)環(huán)境: 開(kāi)發(fā)工具:Visual Studio 2013 .NET Framework版本:4.5 實(shí)現(xiàn)代碼: //第一個(gè)客戶(hù)端的代碼
/// <summary> /// 發(fā)送消息 /// </summary> /// <param name="hWnd">發(fā)送窗口句柄</param> /// <param name="msg">發(fā)送的消息類(lèi)型</param> /// <param name="wParam">附加消息,根據(jù)msg參數(shù)區(qū)分使用</param> /// <param name="lParam">發(fā)送數(shù)據(jù)</param> /// <returns></returns> [DllImport("User32.dll", EntryPoint = "SendMessage")] private static extern int SendMessage(int hWnd, int msg, int wParam, ref COPYDATASTRUCT lParam);
/// <summary> /// 查找窗口句柄 /// </summary> /// <param name="lpClassName">類(lèi)名</param> /// <param name="lpWindowName">窗口標(biāo)題</param> /// <returns></returns> [DllImport("User32.dll", EntryPoint = "FindWindow")] private static extern int FindWindow(string lpClassName, string lpWindowName);
//當(dāng)一個(gè)應(yīng)用程序傳遞數(shù)據(jù)給另一個(gè)應(yīng)用程序時(shí)發(fā)送此消息 const int WM_COPYDATA = 0x004A;
private void btnSend_Click(object sender, EventArgs e) { //根據(jù)標(biāo)題查找到句柄 int hWnd = FindWindow(null, "客戶(hù)端2"); //組織數(shù)據(jù) COPYDATASTRUCT cds; cds.dwData = 0; cds.cbData = System.Text.Encoding.Default.GetBytes(txtMsg.Text).Length + 1; cds.lpData = txtMsg.Text; //發(fā)送 SendMessage(hWnd, WM_COPYDATA, 0, ref cds);
} public struct COPYDATASTRUCT { public int dwData;//若發(fā)送較小數(shù)據(jù)可用此字段傳輸 public int cbData;//發(fā)送數(shù)據(jù)的大?。ㄒ宰止?jié)為單位) [MarshalAs(UnmanagedType.LPStr)] public string lpData;//發(fā)送數(shù)據(jù) }
//第二個(gè)客戶(hù)端的代碼
const int WM_COPYDATA = 0x004A; /// <summary> /// 重新DefWndProc方法,處理接收到的windows消息 /// </summary> /// <param name="m"></param> protected override void DefWndProc(ref System.Windows.Forms.Message m) { switch (m.Msg) { case WM_COPYDATA: COPYDATASTRUCT myStr = new COPYDATASTRUCT(); Type myType = myStr.GetType(); myStr = (COPYDATASTRUCT)m.GetLParam(myType); txtMsg.Text = myStr.lpData; break; default: base.DefWndProc(ref m); break; } }
public struct COPYDATASTRUCT { public int dwData;//若發(fā)送較小數(shù)據(jù)可用此字段傳輸 public int cbData;//發(fā)送數(shù)據(jù)的大?。ㄒ宰止?jié)為單位) [MarshalAs(UnmanagedType.LPStr)] public string lpData;//發(fā)送數(shù)據(jù) }
實(shí)現(xiàn)效果:
這只是SendMessage諸多用法中的一個(gè),,強(qiáng)大之處遠(yuǎn)不于此,后面會(huì)陸續(xù)寫(xiě)出來(lái) 由簡(jiǎn)入繁,,拿來(lái)即用 后續(xù)精彩,,持續(xù)關(guān)注
|