我正在做一个c#程序.我有四种不同的形式.退出表单并不会停止这个过程.我做错了什么?
本文关键字:表单 退出 什么 错了 过程 程序 一个 四种 | 更新日期: 2023-09-27 18:02:50
这是我打开一个新表单的方法
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
//Sets the Add New Button to Color WhiteSmoke
this.button1.BackColor = Color.WhiteSmoke;
//Hides current form (Form 1)
this.Hide();
//Displays Form 2
f2.ShowDialog();
}
这是我关闭窗体的方式。我做错了什么?
private void Form1_Close(object sender, FormClosingEventArgs e)
{
foreach (Form form in Application.OpenForms)
{
Environment.Exit(0);
}
}
不调用Environment.Exit(0)
,而是调用Close():
foreach (Form form in Application.OpenForms)
{
form.Close();
}
另一种选择:
Application.Exit();
尝试将您的代码放入Form1_FormClosing()方法:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
foreach (Form form in Application.OpenForms)
{
// Make sure form is visible before closing //
form.Show();
form.Close();
}
Environment.Exit(0);
}
Form1的关闭事件是不调用,如果窗体是隐藏的。
所以不要隐藏表单。事实上-永远不要隐藏表单:)
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
//Sets the Add New Button to Color WhiteSmoke
this.button1.BackColor = Color.WhiteSmoke;
//Hides current form (Form 1)
this.Hide(); //<-- delete this
//Displays Form 2
f2.ShowDialog();
f2.Dispose(); //<-- necessary when using ShowDialog()
}
并删除所有这些:
private void Form1_Close(object sender, FormClosingEventArgs e)
{
foreach (Form form in Application.OpenForms)
{
Environment.Exit(0);
}
}
这会使进程关闭然后关闭Form1
这里,简单的解决方案是在Form2构造函数中传递Form1对象引用并调用Form1。Close in Form2_Closing Event.
public partial class Form1 : Window
{
public Form1()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Form2 f2 = new Form2(this);
this.Hide();
f2.Show();
}
}
当Form2关闭时,调用Form1关闭事件
public partial class Form2 : Window
{
Form1 frm;
public Form2()
{
InitializeComponent();
}
public Form2(Form1 frm)
{
InitializeComponent();
this.frm = frm;
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
frm.Close();
}
}