Opening (if no instance exists) or Showing on top of all windows (if an instance already exists) of a ChildForm in a MDIParent Form

Ndebata
Posted by Ndebata under Windows Forms category on | Points: 40 | Views : 2938
In this code three windows forms are used
1.Parent ( Which is used as a MDI Parent for rest of the forms)
2.ChildOne and ChildTwo are two child form.
in Parent form two buttons are used named btnChildOne and btnChildTwo.

using System;
using System.Linq;
using System.Windows.Forms;
namespace MDIDemo
{
public partial class Parent : Form
{
public Parent()
{
InitializeComponent();
this.IsMdiContainer = true;
}
private void ShowChild(Form childform)
{
//check any child form is already opened or not
if (this.MdiChildren.Count(cf => cf.ToString().Equals(childform.ToString())) == 0)
{
childform.MdiParent = this;
childform.Show();
}
else
{
//Show this on top of all other form if it has been opened before.
var shownform = this.MdiChildren.FirstOrDefault(cf => cf.ToString().Equals(childform.ToString()));
shownform.Activate();
//dispose this instance as another instance is there.
childform.Dispose();
}
}
private void btnChildOne_Click(object sender, EventArgs e)
{
ShowChild(new ChildOne());
}
private void btnChildTwo_Click(object sender, EventArgs e)
{
ShowChild(new ChildTwo());
}
}
}


Thanks,
Debata

Comments or Responses

Login to post response