main 页面
<Window x:Class="MSMQAPP.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel Orientation="Vertical">
<Button Width="100" Height="30" Content="发送" Click="btn_Send" Margin="0,10,0,0"/>
<TextBox Width="200" Height="20" x:Name="tb_Mess" Margin="0,10,0,0" Text="张三"/>
<Button Width="100" Height="30" Content="接受" Margin="0,10,0,0" Click="btn_Receive"/>
<TextBox Width="200" Height="200" x:Name="tb_receive" Margin="0,10,0,0" AcceptsReturn="True" TextWrapping="Wrap" VerticalScrollBarVisibility="Visible"/>
</StackPanel>
</Grid>
</Window>
mian.cs 页面
namespace MSMQAPP
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
DispatcherTimer dtimer = new DispatcherTimer();
private void btn_Send(object sender, RoutedEventArgs e)
{
dtimer.Tick += dtimer_Tick;
dtimer.Interval = new TimeSpan(0,0,5);
dtimer.Start();
}
void dtimer_Tick(object sender, EventArgs e)
{
if (!MessageQueue.Exists(@".\Private$\zhaozlMSMQ"))
{
using (MessageQueue mq = MessageQueue.Create(@".\Private$\zhaozlMSMQ"))
{
mq.Label = "zhaozlPrivateQueue";
mq.Send("MSMQ Private Message", "zhaozl");
}
}
if (MessageQueue.Exists(@".\Private$\zhaozlMSMQ"))//获得私有的消息队列
{
MessageQueue mq = new MessageQueue(@".\Private$\zhaozlMSMQ");
mq.Send(this.tb_Mess.Text + DateTime.Now.ToString(), "zhaozl");//发送消息到私有的消息队列里
this.tb_Mess.Text = string.Empty;
}
}
DispatcherTimer dtime = new DispatcherTimer();
private void btn_Receive(object sender, RoutedEventArgs e)
{
dtime.Tick += dtime_Tick;
dtime.Interval = new TimeSpan(0, 0, 5);
dtime.Start();
}
void dtime_Tick(object sender, EventArgs e)
{
if (MessageQueue.Exists(@".\Private$\zhaozlMSMQ"))//判断私有消息是否存在
{
using (MessageQueue mq = new MessageQueue(@".\Private$\zhaozlMSMQ"))
{
mq.Formatter = new XmlMessageFormatter(new string[] { "System.String" });//设置消息队列格式化器
MessageEnumerator Me = mq.GetMessageEnumerator2();
while (Me.MoveNext())
{
System.Messaging.Message message = mq.Receive();
this.tb_receive.Text += message.Body + "!";
}
}
}
}
}
}