I need to focus on form if it is already opened else i want to open new form.
I have tried this code to solve my problem but it opens new form instead of focusing already opened form.
foreach (var item in Application.OpenForms)
{
Form form1 = item as Form ;
if (form1 != null)
{
form1.Activate();
break;
}
else
{
form1 = new Form ();
form1.Show();
break;
}
}
My guess is that the problem is that you're only actually looking at the first form - you've got a break
statement in both parts of the if
statement... and you're also just using the general Form
type which is almost certainly inappropriate. You might want:
var form = Application.OpenForms.OfType<MyForm>().FirstOrDefault();
if (form != null)
{
form.Activate();
}
else
{
new MyForm().Show();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With