[英]How to create a function for mdi container
How do I create a function for my following code so that i may not have to write the following whole code to make a form be used as MDICHILD Form. 如何为下面的代码创建一个函数,这样我可能不必编写以下完整代码即可将表单用作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();
}
}
There's nothing really wrong with the code you have. 您拥有的代码并没有真正的错。 You can make it DRY with a bit of reflection: 您可以通过一些反射使其变干:
public Form CreateMdiChild(Type type, bool singleton) {
if (singleton) {
foreach (var child in this.MdiChildren) {
if (child.GetType() == type) {
child.WindowState = FormWindowState.Normal;
child.Show();
child.Activate();
return child;
}
}
}
Form form = (Form)Activator.CreateInstance(type);
form.MdiParent = this;
form.Show();
return form;
}
Usage: 用法:
CreateMdiChild(typeof(Students), true);
Try this 尝试这个
private void CreateMdiChild<T>(ref T t) where T : Form, new()
{
if (t == null || t.IsDisposed)
{
t = new T();
t.MdiParent = this;
t.Show();
}
else
{
if (t.WindowState == FormWindowState.Minimized)
{
t.WindowState = FormWindowState.Normal;
}
else
{
t.Activate();
}
}
}
Usage: 用法:
Students students;
private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
{
CreateMdiChild<Students>(ref students);
}
Use Students as singleton class/form: 将学生用作单例班/形式:
public class Students: Form
{
private static Students _Self;
public static Students ShowOrActivate(Form parent)
{
if (_Self == null)
{
_Self = new Students();
_Self.MdiParent = this;
_Self.Show();
}
else
_Self.Activate();
}
}
Now show the form with 现在显示表格
private void studentsToolStripMenuItem1_Click(object sender, EventArgs e)
{
Students.ShowOrActivate(this);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.