I am a beginner in programming. I try to create small application with many forms. I would like to explain, how to open form with creating instance of this form with using method.
I have actually this:
private void firtsToolStripMenuItem_Click(object sender, EventArgs e)
{
if(myForm == null)
{
myForm = new MyForm();
myForm.MdiParent = this;
myForm.FormClosing += myFormForm_FormClosing;
myForm.Show();
}
else
{
myForm.Activate();
}
}
void myForm_FormClosing(object sender, FormClosingEventArgs e)
{
myForm = null;
}
I want to handle many tool strip menu, and i dont want to wrtite that code in each of them, so I want to write some method for opening any form with another type.
This allows you to display at most one MDI child form of each class:
// Stores references to form of each type:
private Dictionary<Type, Form> _childWindows = new Dictionary<Type, Form>();
private Form ShowForm<T>() where T : Form
{
var formType = typeof(T);
// If we already display a form of given type -> activate it
if (_childWindows.ContainsKey(formType))
{
var form = _childWindows[formType];
form.Activate();
return form;
}
else
{
// Else create a new form instance
var form = (Form) Activator.CreateInstance(typeof(T));
form.MdiParent = this;
form.FormClosing += myForm_FormClosing;
_childWindows[formType] = form;
form.Show();
return form;
}
}
void myForm_FormClosing(object sender, FormClosingEventArgs e)
{
_childWindows.Remove(sender.GetType());
}
Usage:
private void firtsToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = ShowForm<MyForm>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With