由于项目需要,用到了简单的观察者模式,项目中要求主窗口收到消息后,将消息派送出去,然后订阅了消息的窗口接收到消息。

如下图所示。

囧!!!图被网易吃掉了,待补充…

新建一个中间类Watcher

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/// <summary>
/// 定义发布消息的委托
/// </summary>
/// <param name="sender">发布者</param>
/// <param name="msg">消息</param>
public delegate void OnSend(object sender, string msg);
public class Watcher
{
/// <summary>
/// 消息发布的事件
/// </summary>
public static event OnSend messageChange;
public static void SendMessage(object sender, string msg)
{
if (messageChange != null)
{
messageChange(sender, msg);
}
}
}

主窗口接收到消息后派发消息

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
protected override void DefWndProc(ref System.Windows.Forms.Message m)
{
switch (m.Msg)
{
case 0x004A:
// 将返回信息发送给所有能接收CAD消息的窗口
Watcher.SendMessage(this, mystr.lpData);
break;
default:
base.DefWndProc(ref m);
break;
}
}

在接收窗口订阅消息和接收消息

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public ImportTrainControlData()
{
InitializeComponent();
// 订阅消息
Watcher.messageChange += new OnSend(ReciveMessage);
}
/// <summary>
/// 接收消息
/// </summary>
/// <param name="sender"></param>
/// <param name="msg">消息内容</param>
void ReciveMessage(object sender, string msg)
{
// frmMain 为主窗口
frmMain _frmMain = sender as frmMain;
if (_frmMain != null)
{
var keyCode = JsonHelper.GetKeyCode(msg);
if (keyCode == "LoadDisplayDataTable")
{
var info = ObjectFactory.GetService<ICADAPI>().getDisplayDataTable(msg);
BindData(info);
}
}
}