Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focusing on winform if already opened?

Tags:

c#

focus

winforms

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;
            }

        }
like image 836
Michael S. Willy Avatar asked Feb 16 '23 04:02

Michael S. Willy


1 Answers

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();
}
like image 191
Jon Skeet Avatar answered Feb 22 '23 22:02

Jon Skeet