Two Forms in C#
The coding relates to Visual C#.NET 2005
I have two forms (Form1 and Form2). Form2 is called by Form1 as Show()
In Form1 Button-1 ----> Form2 frmform2 = new Form2(this);
frmform2.Show();
Now I can switch back to form1 also without closing the Form2.
I can click on the form1 also.
If I click the Button-1 again in the Form1, another Form2 appears. So it makes two forms.
Can I check whether the Form2 is already invoked and prevent it from appearing again? I want to activate the already opened Form2 but not a new Form2?
Posted May 8, 2008, 2:45 AM
bool formIsOpen = false;
//Iterate through all of the form instances owned by form1
foreach (Form form in this.OwnedForms)
{
if (form is Form2)
{
//Set the check variable
formIsOpen = true;
//Focus the form instance
form.Focus();
//Break from the foreach loop
break;
}
}
//If the form is not open
if (!formIsOpen)
{
//Create a new instance amd show it using this
//current form instance as the owner
Form2 form2 = new Form2();
form2.ShowDialog(this);
}
This will only work when you create an instance of Form2, you specify that the current instance of Form1 is the owner using the form2.ShowDialog(this) line of code.
Narmada kPosted May 8, 2008, 1:06 AM
hi,
instead of using frmform2.show() use frmform2.showdialouge();
ManuelPosted Jul 31, 2007, 3:05 AM
So you could define Form2 first time you use it by checking if it is null.
After that check you jut call Show(). If Form2 is already displayed nothing happens without activating that form.