一般的方法:
在第一个窗口中,名为fristForm,这个窗口有一个按钮,button1.第二个窗口为secondForm.
button1对应的代码为:
Private void button1_Click(object sender,System.EventArgs e)
{
Form frm=new secondForm();
frm.Show();
}
请问要怎么样加代码,当我点击button1的时候,第一个窗口关闭的同时第二个窗口打开。
我这样写
Form frm=new secondForm();
frm.Show();
this.Close();
是错的,因为在打开第二个窗口的同时两个窗口又自动的关闭了。
解决的办法:
我们来重现出这个行为。这是因为FirstForm是应用程序的消息循环主窗口,this.Close方法会关闭这个主窗口,从而关闭整个消息循环。因为 SecondForm跟FirstForm使用同一个消息循环,所以消息循环的结束也就将SecondForm给关闭掉了。
对于这个问题,通常的解决方法是隐藏掉FirstForm,而不是关闭它。如果您一定希望关闭FirstForm,您需要创建另外一个线程,然后使用 Application.Run来在这个新线程里面开启SecondForm的消息循环。您可以使用FirstForm.Hide()方法来实现将 FirstForm隐藏掉。这样就不会关闭掉主窗口和消息循环了。
另外一种方法的示例代码如下:
public void NewMessageLook()
{
Form f=new Form();
Application.Run(f);
}
private void button1_Click(object sender, System.EventArgs e)
{
System.Threading.Thread t=new
System.Threading.Thread( new System.Threading.ThreadStart(NewMessageLook));
t.Start();
this.Close();
}
关闭主窗口而打开另一窗口
最新推荐文章于 2023-06-06 01:09:22 发布