daniyalahmad
daniyalahmad

Reputation: 3843

C# stop calling MDI child again and again

When ever I click on Tool strip menu it displays new form every time.I want to stop it displaying the same form again and again. In the code given the form2 is displaying again and again. I want to stop it so it displays once.

Like :

private void newToolStripMenuItem_Click(object sender, EventArgs e)      
{
  Form2 f = new Form2();
  f.MdiParent=this;
  f.Show();
}

Upvotes: 2

Views: 165

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39132

Another approach would be to declare a variable of type Form2 at class level:

public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private Form2 f2 = null;

    private void newToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (f2 == null || f2.IsDisposed)
        {
            f2 = new Form2();
            f2.MdiParent = this;
            f2.Show();
        }
        else
        {
            if (f2.WindowState == FormWindowState.Minimized)
            {
                f2.WindowState = FormWindowState.Normal;
            }
            f2.Activate();
        }
    }

}

Upvotes: 2

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

You should be able to do something like this:

private void newToolStripMenuItem_Click(object sender, EventArgs e)      
{
    var f2 = this.MdiChildren.OfType<Form2>().FirstOrDefault();
    if (f2 != null)
    {
        f2.Show();
        return;
    }

    Form2 f = new Form2();
    f.MdiParent=this;
    f.Show();
}

This will show the form if it already exists, otherwise create it and show it.

Upvotes: 3

Related Questions