Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

c# - Simplify the creation of MDI child Forms based on their Type

I have an MDI Application and each child Form needs to be initialized using the same operations:

private void button1_Click(object sender, EventArgs e)
{
    frmClient useform=new frmClient();
    useform.MdiParent=this;
    useform.Text=this.Text+" - "+useform.Text;
    useform.Show();
}

I do this for about 5 or 6 different Forms. To avoid repetitions, I have a method to create instances of child Forms:

private void OpenFocus<frmType>()
{
    //iterate child forms and if this type is found, set it as focused and return true
    if (IsFormOpen(typeof(frmType)))
    {
        return;
    }

    var useform = new Form(); 
    switch (typeof(frmType).Name)
    {
        case "frmCompany":
            useform = new frmCompany();
            break;
        case "frmClients":
            useform = new frmClients();
            break;
        /*
            a whole bunch more forms
            ...
        */
        default:
            return;
    }
    useform.MdiParent=this;
    useform.Text=this.Text+" - "+useform.Text;
    useform.Show();
}

Called like:

private void button1_Click(object sender, EventArgs e)
{
    OpenFocus<frmCompany>();
}
private void button2_Click(object sender, EventArgs e)
{
    OpenFocus<frmClients>();
}

I have tried

var useform=Activator.CreateInstance<frmType>();

but it is extremely slow, so am avoiding it.

Any suggestions to improve this? It doesn't feel right.

question from:https://stackoverflow.com/questions/66052616/simplify-the-creation-of-mdi-child-forms-based-on-their-type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can make your method more generic, setting T to the Form Type, create a new Instance of T if one of the same Type doesn't already exist and assign the MdiParent property to the Form instance passed as parameter.
Set any other required property, as the Text you're showing in the question:

private T OpenForm<T>(Form parent) where T : Form, new()
{
    if (Application.OpenForms.OfType<Form>().Any(f => f is T)) return null;

    var child = new T() { MdiParent = parent };
    child.Text = $"{parent.Text} - {child.Text}";
    return child;
}

Then call it as:

OpenForm<frmCompany>(this)?.Show();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...