可以实现跨窗体操作的第二种方法就是消息机制。windows中的应用程序执行是靠消息来驱动的,消息就是一连串的符号和命令。

在C#中,每个窗体都包含了一个消息处理函数,在需要接收消息的情况下,需要重载实现DefWndProc方法。具体使用方法如下:

1、建立“窗体1”,打开代码编写页面

   

View Code
 1 protected override void DefWndProc(ref System.Windows.Forms.Message m)
2 {
3 switch(m.Msg)
4 {
5 case Note.user:
6 {
7 textBox1.Text = "发送消息成功";
8 break;
9 }
10 case Note.test:
11 {
12 textBox1.Text = "测试成功";
13 break;
14 }
15 default:
16 base.DefWndProc(ref m);
17 break;
18 }
19 }

2、编写消息发送方法和自定义消息类型

View Code
 1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Runtime.InteropServices;
6
7 namespace Test跨窗体
8 {
9 public class Note
10 {
11 [DllImport("user32.dll", EntryPoint = "PostMessage")]
12 //PostMessage也可以换成SendMessage
13 private static extern int PostMessage(
14 int hwnd, // handle to destination window
15 int msg, // message
16 int wparam, // first message parameter
17 int lparam // second message parameter 后连个变量可作为传递参数之用
18 );
19 [DllImport("user32.dll", EntryPoint = "FindWindow")]
20 private static extern int FindWindow(string lpclassname, string lpwindowname);//搜索发送消息的目标窗体
21 //定义消息常数 用来标志处理哪类消息的参数
22 public const int user = 0x500;
23 public const int test = user + 1;
24 /// <summary>
25 /// 向窗体发送消息的函数
26 /// </summary>
27 /// <param name="msg"></param>
28 public void sendmsgtomainform(int msg)
29 {
30 int window_handler = FindWindow(null, "Form1");//此处Form1代表的是要搜索的窗体
31 if(window_handler == 0)//不存在当前窗体
32 {
33 //throw new exception("could not find main window!");
34 }
35 else
36 PostMessage(window_handler, msg, 100, 200);
37 }
38 }
39 }

3、在任意方法内调用消息发送函数,参数为自定义的发送消息的类型

     在“Form2”中的button2的click事件中调用消息触发函数:

View Code
 1 private void button2_Click(object sender, EventArgs e)
2 {
3 try
4 {
5 Note note = new Note();
6 note.sendmsgtomainform(Note.test);
7 }
8 catch
9 { }
10 }