在上一章(C# 按Button弹出新的窗体 Show()方法 和 ShowDialog()方法)的基础上,我们实现窗口之间参数的传递,界面如下
先启动Form1,点button1,弹出Form2,在Form2窗口,点Send 铵键,就把67890传回Form1并textbox里显示出来,如何实现呢?
1 先建好Form1和Form2界面,至于如何建立,可以参考章节:C# 按Button弹出新的窗体 Show()方法 和 ShowDialog()方法 , 这里不再详述。
2 主窗口代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 窗口之间参数传递
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Form2 input_macform2;
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.CheckState == CheckState.Checked)
{
input_macform2 = new Form2();
input_macform2.TaskEvent += new TaskDelegate(form2_TaskEvent);
input_macform2.Show();
}
else
{
//没有对form2实例化,会报错
input_macform2.TaskEvent += new TaskDelegate(form2_TaskEvent);
}
}
void form2_TaskEvent(string text)
{
textBox1.Text = text;
}
}
}
3 子窗口代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 窗口之间参数传递
{
public delegate void TaskDelegate(string text);
public partial class Form2 : Form
{
public event TaskDelegate TaskEvent;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TaskEvent(this.textBox1.Text);
// this.Close();
}
}
}