![](/img/trans.png)
[英]how to call a method or function inside MDI main parent I need to instantiate a form on class and new instance parent shoud mainparent?
[英]how to call mdi form by function
如何創建一個跟隨代碼的函數,以便我可以不必編寫以下整個代碼來使表單用作MDICHILD表單。
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();
}
}
雖然我想要這樣
private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
{
CreateMdiChild(Students);
}
和功能應該是這樣的
public void CreateMdiChild(Form form)
{
//expected code
}
您可以使方法通用,例如:
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();
}
}
用法:
private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
{
CreateMdiChildOrActivate(ref this.stu);
}
編輯:
如果您不想為每個表單創建一個類字段,您可以這樣做:
創建一個包含每個表單類型的打開表單的類字典字段:
private Dictionary<Type,Form> openForms = new Dictionary<Type,Form>();
然后將以前的方法更改為:
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();
}
}
現在你可以像這樣調用它:
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();
}
用法
CreateMdiChild<MyForm>()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.