每当在 Windows 窗体 C# 中打开新窗体时,如何Close
后台窗体?
- 它不应该是要关闭的特定形式。
- 每当打开表单时,它都应关闭所有后台表单。
两种方法。
首先是使用这样的Application.OpenForms
:
foreach (Form form in Application.OpenForms)
{
if(Form is YourMainFormClassName) //Check if current form is your main form and do not close it since your app would close. You can use .Hide() if you want
return;
form.Close();
}
另一种方法是使用List
但你不能List<Form>
,因为在删除时,如果你想删除特定的表单,你会有问题,你会喜欢yourList.Remove(this)
它会删除所有具有该表单类的项目。当然,只有当您多次打开一个表单时才会发生这种情况,但为了避免这种情况,我们将使用Form.Tag
属性。
An Object that contains data about the control. The default is null
因此,我们将使用它来存储表单的Id
。
所以现在当我们准备系统时,让我们写它:
首先,我们需要List<Form>
可以从所有类访问,因此我们将像public static
属性一样创建它。
public static class Settings //Class is also static
{
public static List<Form> OpenedForms = new List<Form>();
public static int MaxIdOfOpenedForm() //With this method we check max ID of opened form. We will use it later
{
int max = -1;
foreach(Form f in OpenedForms)
{
if(Convert.ToInt32(f.Tag) > max)
max = Convert.ToInt32(f.Tag);
}
return max;
}
public static void RemoveSpecificForm(Form form) //Remove specific form from list
{
for(int i = 0; i < OpenedForms.Count; i++)
{
if((OpenedForms[i] as Form).Tag == form.Tag)
{
OpenedForms.Remove(form);
return;
}
}
}
public static void CloseAllOpenedForms()
{
for(int i = 0; i < OpenedForms.Count; i++)
{
OpenedForms.Remove(OpenedForms[i]);
}
}
}
现在我们有列表,但每次打开新表单时都需要填充它,因此我们将这样做:
public partial class YourForm
{
public YourForm()
{
InitializeComponents();
this.Tag = Settings.MaxIdOfOpenedForm() + 1; //We are setting Tag of newly opened form
Settings.OpenedForms.Add(this); //Adding new form to opened forms.
}
}
当我们关闭表单时,我们需要从列表中删除表单:
private void YourFormClosed(object sender, EventArgs e)
{
RemoveSpecificForm(this);
}
当我们设置它时,只需调用CloseAllOpenedForms()
.
此方法可能会在性能上有所改进,但这是基本的,您可以进一步扩展它。
并且只有一个表单可以处于活动状态并在前台,因此在打开新表单时,您可以关闭前一个表单:
在您的主窗体中:
Form previous_form = null;
以及创建任何表单时:
if( previous_form != null)
previous_form.Close();
SomeForm someform = new SomeForm();
previsous_form = some_form;
someform.Show();