Whilst developing a current project which contains a number of WinForms, I’m finding myself becoming cluttered with lines of code simply to handle open / close events for the forms. Currently I’m handling them like so..
//Declare forms
myForm mForm1;
myForm2 mForm2;
private void btnSomething_Click(object sender, EventArgs e)
{
if (mForm1 == null)
{
mForm1 = new myForm();
mForm1.FormClosed += new FormClosedEventHandler(mForm1_FormClosed);
mForm1.Show();
}
else
if (mForm1.WindowState == FormWindowState.Minimized)
mForm1.WindowState = FormWindowState.Normal;
mForm1.Focus();
}
void mForm1_FormClosed(object sender, FormClosedEventArgs e)
{
mForm1 = null;
}
And then another set of voids to handle each forms open / close. Now imagine that instead of 2 forms, I’ve got, say, 5 forms. Now I’m even more cluttered. Is there a way to generalize this to have all forms have the same event handlers?
I’ve thought of perhaps using the object sender in an “as” statement, but i’m not sure how i’d find the relevant declared form instance from there.
sender as (form)
Any ideas?
You can generalize that code easily:
If you want to further generalize the closed event handler, you should consider moving forms’ declarations to some sort of an array, list of dictionary. That way you can easily generalize that method.
EDIT: converted the ShowOrUpdateForm function to generic.