Visual Studio 2013(VS2012、VS2010、VS2008等其他开发环境均可)。
微软消息服务(MSMQ,具体安装方法见参考资料)。
启动VS,新建WinForm项目,命名为MSMQ,用来发送消息,如下:
以新建窗口的方式启动VS,新建WinForm项目,命名为MSMQ2,用来接收消息,如下:
以上两个项目中均添加,System.Messaging引用,如下图:
MSMQ项目窗口设计,如下图:
MSMQ2项目窗口设计,如下图:
MSMQ代码如下:namespace MSMQ{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } MessageQueue mq; private void Form1_Load(object sender, EventArgs e) { //新建消息循环队列或连接到已有的消息队列 string path = '.\\private$\\killf'; if (MessageQueue.Exists(path)) { mq = new MessageQueue(path); } else { mq = MessageQueue.Create(path); } mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); } private void button2_Click(object sender, EventArgs e) { mq.Send(textBox1 .Text ); } }}
MSMQ2代码如下:namespace MSMQ2{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } MessageQueue mq; private void Form1_Load(object sender, EventArgs e) { //新建消息循环队列或连接到已有的消息队列 string path = '.\\private$\\killf'; if (MessageQueue.Exists(path)) { mq = new MessageQueue(path); } else { mq = MessageQueue.Create(path); } mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); mq.ReceiveCompleted += mq_ReceiveCompleted; mq.BeginReceive(); } void mq_ReceiveCompleted(object sender, ReceiveCompletedEventArgs e) { //throw new NotImplementedException(); MessageQueue mq = (MessageQueue)sender; System .Messaging .Message m = mq.EndReceive(e.AsyncResult); //处理消息 string str = m.Body.ToString(); this.textBox1.Invoke(new Action
调试运行:分别启动MSMQ和MSMQ2,在MSMQ中的TextBox中输入字符串,然后点击发送,MSMQ2将会收到消息,并显示在TextBox控件中,如下图。
需要引用System.Messaging文件,并且在代码中好要Using一下。
使用System.Messaging时需要安装MSMQ消息服务。
在不是创建控件的线程中无法调用控件的方法,使用Control.Invoke即可。