I had a similar issue in the past, first thing that crossed my mind back there was to use System.Reflection
but it is impossible because you can not identify in run time what instance was created.
I have not found any "magic" solution for that issue, but The most easy and safe solution I found was to extend Form
base class (to my custom SuperForm
) and using this base class to coordinate and update a static list of all instances from this base class (by overriding OnLoad()
and OnClosed()
methods).
Obviously all application forms must inherit from SuperForm
.
Also, I found that in a vast winforms application, making all forms to inherit a class that you extend by yourself is a good practice because it gives you much more control over the application and can make your life easier in the future.
here is a sample of the architecture:
SuperForm Class:
public class SuperForm : Form
{
private bool _isFormActive = false;
public bool isFormActive
{
get
{
return this._isFormActive;
}
set
{
this._isFormActive = value;
}
}
protected override void OnLoad(EventArgs e)
{
this.isFormActive = true;
AppForms.Add(this);
base.OnLoad(e);
}
protected override void OnClosed(EventArgs e)
{
this.isFormActive = false;
AppForms.Remove(this);
base.OnClosed(e);
}
}
Static class with static list to handle application forms instances:
public static class AppForms
{
private static List<SuperForm> _AppFormsList;
public static List<SuperForm> AppFormsList
{
get
{
if (_AppFormsList == null)
{
_AppFormsList = new List<SuperForm>();
}
return _AppFormsList;
}
set
{
_AppFormsList = value;
}
}
public static void Add(SuperForm instance)
{
AppFormsList.Add(instance);
}
public static void Remove(SuperForm instance)
{
AppFormsList.Remove(instance);
}
}
Implementation:
public partial class Form1 : SuperForm
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
// you dont have to use polymorphism...
SuperForm f = new Form2();
f.Show();
}
private void button2_Click(object sender, EventArgs e)
{
// you dont have to use polymorphism...
SuperForm f = new Form3();
f.Show();
}
private void button3_Click(object sender, EventArgs e)
{
// show all the forms that are active
foreach (var frm in AppForms.AppFormsList)
{
MessageBox.Show(((SuperForm)frm).isFormActive.ToString());
}
}
}