近来因项目的需要,触及到程序进程之间的消息通讯,根据应用的简繁程序,归纳成简易方案与高级方案。本文介绍简易方案,高级方案于下一篇中整理。
以下代码包括共用结构定义,发送方,接收方三个部份的代码:
结构定义:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace Common
{
//发送共享消息的结构
public struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
[MarshalAs(UnmanagedType.LPStr)]
public string lpData;
}
}
发送方:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
namespace ProjectA
{
public partial class SenderForm : Form
{
const int WM_COPYDATA = 0x004A;
//发送消息的API
[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 Common.COPYDATASTRUCT lParam // second message parameter
);
//通过窗体标题找出窗体的Handle
[DllImport("User32.dll", EntryPoint = "FindWindow")]
private static extern int FindWindow(string lpClassName, string lpWindowName);
public SenderForm()
{
InitializeComponent();
}
private void btnSendMsg_Click(object sender, EventArgs e)
{
//找出接收方窗体的FormHandle
int WINDOW_HANDLER = FindWindow(null, @"接收方");
if (WINDOW_HANDLER != 0)
{
byte[] sarr = System.Text.Encoding.Default.GetBytes(this.txtMsg.Text);
int len = sarr.Length;
Common.COPYDATASTRUCT cds;
cds.dwData = (IntPtr)100;
cds.lpData = this.txtMsg.Text;
cds.cbData = len + 1;
//发送消息
SendMessage(WINDOW_HANDLER, WM_COPYDATA, 0, ref cds);
}
}
}
}
接收方:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
namespace ProjectB
{
public partial class ReceiverForm : Form
{
const int WM_COPYDATA = 0x004A;
public ReceiverForm()
{
InitializeComponent();
}
protected override void DefWndProc(ref System.Windows.Forms.Message m)
{
switch (m.Msg)
{
case WM_COPYDATA:
Common.COPYDATASTRUCT mystr = new Common.COPYDATASTRUCT();
Type mytype = mystr.GetType();
mystr = (Common.COPYDATASTRUCT)m.GetLParam(mytype);
this.txtMsg.Text = mystr.lpData;
break;
default:
base.DefWndProc(ref m);
break;
}
}
}
}