How do I create a function for following code so that i may not have to write the following whole code to make a form be used as MDICHILD Form.
Students stu = null;
private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
{
if (stu == null || stu.IsDisposed)
{
stu = new Students();
stu.MdiParent = this;
stu.Show();
}
else
{
stu.Activate();
}
}
while I want it like this
private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
{
CreateMdiChild(Students);
}
and function should be like this
public void CreateMdiChild(Form form)
{
//expected code
}
You could make the method generic, eg :
public void CreateMdiChildOrActivate<T>(ref T instance) where T : Form, new()
{
if (instance == null || instance.IsDisposed)
{
instance = new T();
instance.MdiParent = this;
instance.Show();
}
else
{
instance.Activate();
}
}
Usage:
private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
{
CreateMdiChildOrActivate(ref this.stu);
}
EDIT :
If you don't want to create a class field for each form, you can do in this way:
Create a class dictionary field containing the open form for each form-type:
private Dictionary<Type,Form> openForms = new Dictionary<Type,Form>();
Then change the previous method to:
public void CreateMdiChildOrActivate<T>() where T : Form, new()
{
Form instance;
openForms.TryGetValue(typeof(T), out instance);
if (instance == null || instance.IsDisposed)
{
instance = new T();
openForms[typeof(T)] = instance;
instance.MdiParent = this;
instance.Show();
}
else
{
instance.Activate();
}
}
Now you can call it like this:
private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
{
CreateMdiChildOrActivate<Student>();
}
public void CreateMdiChild<T>(Form f) where T : Form, new()
{
foreach (Form frm in f.MdiChildren)
{
if (frm.GetType() == typeof(T))
{
if (frm.WindowState == FormWindowState.Minimized)
{
frm.WindowState = FormWindowState.Normal;
}
else
{
frm.Activate();
}
return;
}
}
T t = new T();
t.MdiParent = f;
t.Show();
}
Usage
CreateMdiChild<MyForm>()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.