发消息
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.Messaging;namespace WindowsFormsApplication1{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } string QueuePath = ".\\private$\\test"; IMessageFormatter formatter = new System.Messaging.BinaryMessageFormatter(); private void button1_Click(object sender, EventArgs e) { MessageQueue queue; if (!MessageQueue.Exists(QueuePath)) { queue = MessageQueue.Create(QueuePath); queue.SetPermissions("Administrators", MessageQueueAccessRights.FullControl); queue.Label = QueuePath; } System.Messaging.Message message = new System.Messaging.Message(); message.Body = richTextBox1.Text; message.Formatter = formatter; if (!MessageQueue.Exists(QueuePath)) { return; } queue = new System.Messaging.MessageQueue(QueuePath); queue.Send(message); } }}
收消息
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;using System.Messaging;namespace WindowsFormsApplication2{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } string QueuePath = ".\\private$\\test"; IMessageFormatter formatter = new System.Messaging.BinaryMessageFormatter(); private void Form1_Load(object sender, EventArgs e) { } private object obj = new object(); private void MessageQueueReceive() { if (!MessageQueue.Exists(QueuePath)) { return; } MessageQueue queue = new MessageQueue(QueuePath); System.Messaging.Message message = queue.Receive(); message.Formatter = formatter; lock (obj)//加锁 { WriteLog(message.Body.ToString());//给你的控件赋值 } MessageQueueReceive(); } private void button1_Click(object sender, EventArgs e) { Thread myThread = new Thread(new ThreadStart(MessageQueueReceive)); myThread.Start(); } //定义一个委托 private delegate void WriteLogHandle(string format); //输出 private void WriteLog(string msg) { if (richTextBox1.InvokeRequired) { richTextBox1.BeginInvoke(new WriteLogHandle(WriteLog), msg); } else { richTextBox1.AppendText(string.Format(msg)); } } }}