I have the code:
private void Button1_Click (object sender, EventArgs e)
(
Form2 f2 = new Form2 ();
f2.Show ();
)
how to make so that Form2 when you click on Button1 not opened for the second time, if it is open?
sorry for bad english
I have the code:
private void Button1_Click (object sender, EventArgs e)
(
Form2 f2 = new Form2 ();
f2.Show ();
)
how to make so that Form2 when you click on Button1 not opened for the second time, if it is open?
sorry for bad english
Assuming your main form class is MyForm, update your code as below. The idea is to maintain only single instance of the Form2.
public partial class MyForm: Form
{
public MyForm()
{
InitializeComponent();
}
private Form2 f2;
private void Button1_Click (object sender, EventArgs e)
(
if (null == f2 || f2.IsDisposed)
f2 = new Form2();
f2.Show ();
)
}
You have to make sure you only have 1 instance of Form2
created. One way to do this is to move the object declaration and instantiation to a private variable and in your click event handler simply call the Show()
method:
private Form2 f2 = new Form2();
private void Button1_Click (object sender, EventArgs e)
(
if(f2 == null)
{
f2 = new Form2();
}
f2.Show ();
)
I didn't checked if Visible property will work for Form, but you can try this.
public partial class MyForm: Form
{
public MyForm()
{
InitializeComponent();
}
Form2 f2 = null;
private void Button1_Click (object sender, EventArgs e)
(
if(f2 == null)
f2 = new Form2();
if(!f2.Visible)
f2.Show ();
)
}
Similar to the existing answers, but with an extra event handler:
private Form f2 = null;
private void Button1_Click (object sender, EventArgs e)
{
if (f2 == null)
{
f2 = new Form2();
// Make sure we don't try to re-show a closed form
f2.FormClosed += delegate { f2 = null; };
}
f2.Show ();
}
This code will open form. If previously form not oppened in application.
private void button1_Click(object sender, EventArgs e)
{
bool result = false;
foreach (Form form in Application.OpenForms)
{
if (form.GetType() == typeof(Form2))
result = true;
}
if (result == false)
new Form2().Show();
}