How to get active objects of a Form in c#?
What I wa开发者_如何学Pythonnt to do is - if I click menu of Main(MDI) Form its do not create new object of the specified form on that menu if form is already opened. Please help.
You need to keep a reference to the open form somewhere (possibly a field) and if it is set, not create a new instance.
Pseudo code:
// a field
Form myForm;
// In the method where you would normally instantiate the form:
if (myForm == null)
myForm = new MyForm();
myForm.Show();
Sample :
private void buttonUnits_Click(object sender, EventArgs e)
{
if (this.unitsForm == null)
{
this.unitsForm = new UnitsForm();
this.unitsForm.MdiParent = this;
this.unitsForm.Disposed += new EventHandler(unitsForm_Disposed);
this.unitsForm.Dock = DockStyle.Fill;
}
this.unitsForm.Show();
this.unitsForm.BringToFront();
this.unitsForm.Focus();
}
void unitsForm_Disposed(object sender, EventArgs e)
{
this.unitsForm = null;
}
Application.OpenForms hold list of all open forms just iterate over it and check if it cointains form of type you whant to create if it contains do nothing. Something like this
private void button1_Click(object sender, EventArgs e)
{
foreach (Form form in Application.OpenForms)
{
if (form is FormTypeToOpen )
return;
}
FormTypeToOpen newForm = new FormTypeToOpen();
this.newForm .Show();
this.newForm.BringToFront();
this.newForm.Focus();
}
Best Regards,
Iordan
Create one object of your opening form like below Form1 frm;
in you Menu click Handler check for instance of the form liek
if(frm ==null)
frm = new Form1();
ok we got the new of the Form1. so we can now show the form.
use frm.Show()
or
frm.ShowDialog();
condition : if you are using frm.Close(); then use need to create object and show it else if u are using frm.hide();
just simple use frm.show();
精彩评论