我们在开发WinForm程序的时候经常会遇到这样一个问题,当用户在主窗体点击一个按钮,需要弹出一个子窗体让用户输入信息,然后在子窗体点击确定后把刚才输入的信息返回到主窗体的界面上。这个效果我暂时知道有2中方法可以实现,第一种是通过事件,第二种是通过using。下面演示第二种方法
1:这是Form2的代码
就简单的一个输入框和一个和两个button
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form2 : Form
{
public Form3()
{
InitializeComponent();
}
public string str = string.Empty;
private void button1_Click(object sender, EventArgs e)
{
str = textBox1.Text;
this.DialogResult = DialogResult.OK;
}
private void button2_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form2 : Form
{
public Form3()
{
InitializeComponent();
}
public string str = string.Empty;
private void button1_Click(object sender, EventArgs e)
{
str = textBox1.Text;
this.DialogResult = DialogResult.OK;
}
private void button2_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
}
}
}

2:下面是Form1的Button_Click代码
using (Form3 f3 = new Form3())
{
f3.ShowDialog();
string str = f3.str;
if (f3.DialogResult == DialogResult.OK)
{
MessageBox.Show(str);
}
}
{
f3.ShowDialog();
string str = f3.str;
if (f3.DialogResult == DialogResult.OK)
{
MessageBox.Show(str);
}
}
实现的效果是点击Form1的button后,会弹出Form2,在Form2里输入信息点击OK,Form1会弹出信息,点击Cancel这Form2就关闭,结束声明周期(Using的作用)