using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Messaging; namespace MSMQ { public partial class MsMq { //通过Create方法创建使用指定路径的新消息队列 /**/ /// <summary> /// 通过Create方法创建使用指定路径的新消息队列 /// </summary> /// <param name="queuePath"></param> public static void Createqueue(string queuePath) { try { if (!MessageQueue.Exists(queuePath)) { MessageQueue.Create(@".\private$\myQueue"); } else { MessageBox.Show(queuePath + "已经存在!"); } } catch (MessageQueueException e) { MessageBox.Show(e.Message); } } /**/ /// <summary> /// 连接消息队列并发送消息到队列 /// </summary> public static void SendMessage() { try { //连接到本地的队列 MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue"); MessageQueueTransaction myTransaction = new MessageQueueTransaction(); System.Messaging.Message myMessage = new System.Messaging.Message(); myMessage.Body = System.Guid.NewGuid().ToString() + "消息内容"; myMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); //发送消息到队列中 myQueue.Send(myMessage); MessageBox.Show("消息发送成功"); } catch (ArgumentException e) { MessageBox.Show(e.Message); } } /**/ /// <summary> /// 连接消息队列并从队列中接收消息 /// </summary> public static void ReceiveMessage() { //连接到本地队列 MessageQueue myQueue = new MessageQueue(".\\private$\\myQueue"); if (message.Length == 0) { MessageBox.Show("队列中没有任何消息!"); return; } myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); try { //从队列中接收消息 System.Messaging.Message myMessage = myQueue.Receive(); string context = (string)myMessage.Body; //获取消息的内容 //Console.WriteLine("消息内容为:" + context); MessageBox.Show("消息内容为:" + context); } catch (MessageQueueException e) { MessageBox.Show(e.Message); } catch (InvalidCastException e) { MessageBox.Show(e.Message); } } } }