如果被调用的窗口已经在运行,然后关闭它并运行新调用的窗口
在我的应用程序几次我必须调用一个窗口(类)。这个窗口的工作是显示一个单词的含义。当我再次呼叫该窗口时,会显示一个新窗口,但前一个窗口也会显示。我有两个表格form1
,form2
。如果被调用的窗口已经在运行,然后关闭它并运行新调用的窗口
Form1中就是这样:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
Form2 s = new Form2(a);// it will be called as many time as i click
s.Show();
}
}
Form2的是这样的:
public partial class Form2 : Form
{
public Form2(string s)
{
InitializeComponent();
label1.Text = s;
}
}
我想是这里面Form1中如果我叫窗口2就说明,但如果我再次调用窗口2之前的窗口2窗口将自动关闭,新的form2窗口将显示而不是前一个窗口。 我该怎么做?
这里是存放在一流水平的窗体2参考的例子,如已在其他人所说:
public partial class Form1 : Form
{
private Form2 f2 = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (f2 != null && !f2.IsDisposed)
{
f2.Dispose();
}
string a = textBox1.Text;
f2 = new Form2(a);
f2.Show();
}
}
我想要的是,如果我打电话form2它内部form1它显示,但如果我再次调用form2以前的form2窗口将自动关闭和新的form2窗口将显示,而不是以前的 – DarkenShooter 2013-05-09 15:31:33
Gotcha ...误读了这个问题。代码已更新。 – 2013-05-09 15:35:48
我认为你应该考虑使用单例模式。
你可以这样实现它:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
Form2.ShowMeaning(a);// it will be called as many time as you click
}
}
1和Form 2
public partial class Form2 : Form
{
private static readonly Form2 _formInstance = new Form2();
private Form2()
{
InitializeComponent();
}
private void LoadMeaning(string s)
{
label1.Text = s;
}
//Override method to prevent disposing the form when closing.
protected override void OnClosing(CancelEventArgs e)
{
e.Cancel = true;
this.Hide();
}
public static void ShowMeaning(string s)
{
_formInstance.LoadMeaning(s);
_formInstance.Show();
}
}
希望它能帮助。
看我有2个窗体名为form1,form2。在form1中“show_meaning s = new show_meaning(x); s.Show();”被称为多次,因为我想。但show_meaning(x)是insid form2.can你给任何简单的方法呢? @VahidND – DarkenShooter 2013-05-09 13:53:25
您对show_meaning()的定义没有定义返回值,所以我将其视为构造函数。为了更好地理解,我重命名方法以匹配您的命名,但如果您为form2提供完整代码,我可能会进一步帮助您。 – VahidNaderi 2013-05-09 14:59:28
我编辑了我的问题。请看看。@ VahidND – DarkenShooter 2013-05-09 15:06:19
不要创建每次一个新窗口((X)''新show_meaning),并显示相同的表单实例。 – I4V 2013-05-09 08:07:19
+1 @ l4v。将引用单词含义表单存储为类级变量,并在每次需要时引用它。 – Adrian 2013-05-09 08:11:10
并使用FormClosed事件来知道该窗口已被用户关闭,并将该参考设置回null。 – 2013-05-09 09:52:58