How to hide multiple forms with one click in Visual Studio?
Try following code:
public static void closeAllOpenedForms()
{
FormCollection FM = Application.OpenForms;
if (FM.Count > 1)
{
for (int i = (FM.Count); i > 1; i--)
{
Form sForm = Application.OpenForms[i - 1];
sForm.Close();
}
}
}
You can check/clone/test this code on https://github.com/JomaStackOverflowAnswers/HideForms
If you need to reuse the opened form you can hide/show as neeeded. But if you create new forms everytime is recommended to close the forms(not hide).
FormMain
namespace HideForms
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void buttonOpen_Click(object sender, EventArgs e)
{
Employee employee = new Employee("123");
FormViewEmployee formViewEmployee = new FormViewEmployee(employee);
FormViewNewUpdates formViewNewUpdates = new FormViewNewUpdates(employee, this, new List<Form>{ formViewEmployee });
formViewEmployee.Show();
formViewNewUpdates.Show();
Hide();
}
}
}
FormViewEmployee
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HideForms
{
public partial class FormViewEmployee : Form
{
private readonly Employee employee;
public FormViewEmployee(Employee employee)
{
InitializeComponent();
this.employee = employee;
}
}
}
FormViewNewUpdates
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace HideForms
{
public partial class FormViewNewUpdates : Form
{
private readonly Employee employee;
private readonly Form parent;
private readonly List<Form> formsToClose;
public FormViewNewUpdates(Employee employee, Form parent, List<Form> formsToClose)
{
InitializeComponent();
this.employee = employee;
this.parent = parent;
this.formsToClose = formsToClose;
}
private void buttonClose_Click(object sender, EventArgs e)
{
foreach(var form in formsToClose)
{
form.Close();//form.Hide(); //Hide in case you need to reuse the form.
}
Close();
parent.Show();// Show the parent form.
}
private void FormViewNewUpdates_FormClosing(object sender, FormClosingEventArgs e)
{
foreach (var form in formsToClose)
{
form.Close();
}
parent.Show();
}
}
}
Output
FormMain When click in open button, it opens FormViewEmployee, FormViewNewUpdates instances.
FormViewEmployee, FormViewNewUpdates instances
When click in Close All button it close both instances and show FormMain instance.
2
References
Control.Hide
Form.Close