0
点赞
收藏
分享

微信扫一扫

C# winform 主窗体与子窗体互相传递消息的例子 (二)


子窗体向主窗体传递信息
描述:主窗体form1上有button1,点击button1,则弹出子窗体form2。
form2上有随便一个button2
form1上还有另外一个text1

要求点击button2,则text1文本框的内容变为 button2点击时候传递过来的内容。
也就是子窗体。

参见上一篇文章,最后说了如果按照文章一里的说法,从主窗体传消息到子窗体,不难。
但是同样的写法,从子窗体传递到主窗体,主窗体就不能正常显示,如实时改变text的值等,即不能正常访问。

以下是一个不能 正常访问的例子。

Form1.cs

using System;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}



#region

public static Form1 instance;

public static Form1 CreateForm()
{
if (instance == null || instance.IsDisposed)
{
instance = new Form1();
}
return instance;
}
#endregion



private void button1_Click(object sender, EventArgs e)
{

Form2 form2 = new Form2();
//就算把form2中的这个event注册在这里,也是不行的,已亲测。
//form2.Slave2MainMsgEvent += Form1.CreateForm().textChange;
form2.Show();
}



public void textChange(object sender, EventArgs e)
{
var a = e as MyEventArg;
//textBox1.Text = a.Text; 无法访问
MessageBox.Show(a.Text); //可以访问

Form2.cs

using System;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}

public event EventHandler Slave2MainMsgEvent;

private void button1_Click(object sender, EventArgs e)
{
MyEventArg eee = new MyEventArg()
{
Text = DateTime.Now.Second.ToString()
};

Slave2MainMsgEvent.Invoke(this, eee);
}

private void Form2_Load(object

MyEventArg.cs

using System;

namespace WindowsFormsApp1
class MyEventArg : EventArgs
//传递主窗体的数据信息
public string Text { get; set; }
}
}

特别注意一下,这里面的单例模式的写法也没有什么不好理解的,因为不这么写,就没法写Form2.cs里的这一行:

Slave2MainMsgEvent += Form1.CreateForm().textChange;

总之,这种写法是不能如愿将子窗体传来的信息实时显示在主窗体的控件上的。


举报

相关推荐

0 条评论