How to check if a windows form is already open, and close it if it is?

C#Winforms

C# Problem Overview


I have a form "fm" that is a simple info window that opens every 10 mins (fm.Show();).

How I can make that every 10 mins it will check if the form "fm" is open and if it is open it closes it and open it again!

Now the form fm is always created with form fm = new form();
so when I try to check if the form is open it will always be false and open a new window even if there is one form before!

I need to have a tool to give it a unique identity and then check if this form with unique identity is opened or not!

I do not want to just update the data on the form (fm), because I have a complicated info with buttons.

The form name is "UpdateWindow"

Thanks

C# Solutions


Solution 1 - C#

maybe this helps:

FormCollection fc = Application.OpenForms;

foreach (Form frm in fc)
{
//iterate through
     if (frm.Name == "YourFormName")
     {
         bFormNameOpen = true;
     }
}

Some code in the foreach to detect the specific form and it could be done. Untested though.

Found on http://bytes.com/topic/c-sharp/answers/591308-iterating-all-open-forms

Solution 2 - C#

I know I am late... But for those who are curious... This is another way

if (Application.OpenForms.OfType<UpdateWindow>().Count() == 1)
    Application.OpenForms.OfType<UpdateWindow>().First().Close();

UpdateWindow frm = new UpdateWindow()
frm.Show();

Solution 3 - C#

Suppose if we are calling a form from a menu click on MDI form, then we need to create the instance declaration of that form at top level like this:

Form1 fm = null;

Then we need to define the menu click event to call the Form1 as follows:

private void form1ToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (fm == null|| fm.Text=="")
    {
        fm = new Form1();              
        fm.MdiParent = this;
        fm.Dock = DockStyle.Fill;
        fm.Show();
    }
    else if (CheckOpened(fm.Text))
    {
        fm.WindowState = FormWindowState.Normal;
        fm.Dock = DockStyle.Fill;
        fm.Show();
        fm.Focus();               
    }                   
}

The CheckOpened defined to check the Form1 is already opened or not:

private bool CheckOpened(string name)
{
    FormCollection fc = Application.OpenForms;

    foreach (Form frm in fc)
    {
        if (frm.Text == name)
        {
            return true; 
        }
    }
    return false;
}

Hope this will solve the issues on creating multiple instance of a form also getting focus to the Form1 on menu click if it is already opened or minimized.

Solution 4 - C#

I'm not sure that I understand the statement. Hope this helps. If you want to operate with only one instance of this form you should prevent Form.Dispose call on user close. In order to do this, you can handle child form's Closing event.

private void ChildForm_FormClosing(object sender, FormClosingEventArgs e)
{
    this.Hide();
    e.Cancel = true;
}

And then you don't need to create new instances of frm. Just call Show method on the instance.

You can check Form.Visible property to check if the form open at the moment.

private ChildForm form = new ChildForm();

private void ReopenChildForm()
{
    if(form.Visible)
    {
        form.Hide();
    }
    //Update form information
    form.Show();
}

Actually, I still don't understand why don't you just update the data on the form.

Solution 5 - C#

Form fc = Application.OpenForms["UpdateWindow"]; 

if (fc != null) 
   fc.Close(); 

fc.Show();

Solution 6 - C#

try this , no need to iterate through the forms :

if(Application.OpenForms["<your_form_name>"] != null){

   //Your form is already open

}
else {
  
  //Your form isn't open

}

Solution 7 - C#

Form1 fc = Application.OpenForms["Form1 "] != null ? (Form1 ) Application.OpenForms["Form1 "] : null;
if (fc != null)
{
    fc.Close();
}

It will close the form1 you can open that form again if you want it using :

Form1 frm = New Form1();
frm.show();

Solution 8 - C#

if (Application.OpenForms["Form_NAME"] == null)
{
   new Form_NAME().Show();
}

If the form instance is not open it will enter the IF loop.

Solution 9 - C#

try this MDICHILD function

public void mdiChild(Form mdiParent, Form mdiChild)
{
    foreach (Form frm in mdiParent.MdiChildren)
    {
        // check if name equals
        if (frm.Name == mdiChild.Name)
        {
            //close if found

            frm.Close();

            return;
        }
    }

    mdiChild.MdiParent = mdiParent;

    mdiChild.Show();

    mdiChild.BringToFront();
}

Solution 10 - C#

if( ((Form1)Application.OpenForms["Form1"]).Visible == true)
    //form is visible
else
    //form is invisible

where Form1 is the name of your form.

Solution 11 - C#

Try this, it will work :

//inside main class
Form1 Fm1 = new Form1();<br>

//in button click
if (Fm1.IsDisposed)
{
    Fm1 = new Form();
}
Fm1.Show();
Fm1.BringToFront();
Fm1.Activate();

Solution 12 - C#

> I think my method is the simplest.

    Form2 form2 = null;
    private void SwitchFormShowClose_Click(object sender, EventArgs e)
    {  
        if(form2 == null){
            form2 = new Form2();
            form2.Show();
        }
        else{
            form2.Close();
            form2 = null;
        }
    }

Solution 13 - C#

Try to wire below,

private void frmMyForm_Deactivate(object sender, EventArgs e)
    {
        // Raise your flag here.
    }

By wiring above event, it will tell you whenever the form is minimized, partially/totally hided by another form.

Solution 14 - C#

This is what I used to close all open forms (except for the main form)

    private void CloseOpenForms()
    {

           // Close all open forms - except for the main form.  (This is usually OpenForms[0].
           // Closing a form decrmements the OpenForms count
           while (Application.OpenForms.Count > 1)
           {
               Application.OpenForms[Application.OpenForms.Count-1].Close();
           }
    }

Solution 15 - C#

Funny, I had to add to this thread.

  1. Add a global var on form.show() and clear out the var on form.close()

  2. On the parent form add a timer. Keep the child form open and update your data every 10 min.

  3. put timer on the child form to go update data on itself.

Solution 16 - C#

*** Hope This will work for u**

System.Windows.Forms.Form f1 = System.Windows.Forms.Application.OpenForms["Order"];
if(((Order)f1)!=null)
{
//open Form
}
else
{
//not open
}

Solution 17 - C#

try this

 bool IsOpen = false;
    foreach (Form f in Application.OpenForms)
    {
        if (f.Text == "Form2")
        {
            IsOpen = true;
            f.Focus();
            break;
        }
    }
 
    if (IsOpen == false)
    {
        Form2 f2 = new Form2();
        f2.MdiParent = this;
        f2.Show();
    }

Solution 18 - C#

 private static Form IsFormAlreadyOpen(Type formType)
 {
     return Application.OpenForms.Cast<Form>().FirstOrDefault(openForm => openForm.GetType() == formType);
 }

Solution 19 - C#

Form only once

If your goal is to diallow multiple instaces of a form, consider following ...

public class MyForm : Form
{
    private static MyForm alreadyOpened = null;

    public MyForm()
    {
        // If the form already exists, and has not been closed
        if (alreadyOpened != null && !alreadyOpened.IsDisposed)
        {
            alreadyOpened.Focus();            // Bring the old one to top
            Shown += (s, e) => this.Close();  // and destroy the new one.
            return;
        }           

        // Otherwise store this one as reference
        alreadyOpened = this;  

        // Initialization
        InitializeComponent();
    }
}

Solution 20 - C#

Form user_rpt = Application.OpenForms["frmUesr_reports"];
        if (user_rpt == null)
        {
            /// Do Something here
        }

Try This This is the short idea to check Form open or not open

Solution 21 - C#

In my app I had a mainmenu form that had buttons to navigate to an assortment of other forms (aka sub-forms). I wanted only one instance of each sub-form to be running at a time. Plus I wanted to ensure if a user attempted to launch a sub-form already in existence, that the sub-form would be forced to show "front¢er" if minimized or behind other app windows. Using the currently most upvoted answers, I refactored their answers into this:

private void btnOpenSubForm_Click(object sender, EventArgs e)
    {

        Form fsf = Application.OpenForms["formSubForm"];

        if (fsf != null)
        {
            fsf.WindowState = FormWindowState.Normal;
            fsf.Show();
            fsf.TopMost = true;
        }
        else
        {
            Form formSubForm = new FormSubForm();
            formSubForm.Show();
            formSubForm.TopMost = true;
        }
    }

Solution 22 - C#

This worked form me:

public void DetectOpenedForm()
{
    FormCollection AllForms = Application.OpenForms;
    Boolean FormOpen = false;
    Form OpenedForm = new Form();
    foreach (Form form in AllForms)
    {
        if (form.Name == "YourFormName")
        {
            OpenedForm = form;
            FormOpen = true;
        }
    }
    if (FormOpen == true)
    {
        OpenedForm.Close();
    }
}

Solution 23 - C#

The below actually works very well.

private void networkInformationToolStripMenuItem_Click(object sender, EventArgs e)
{
    var _open = false;
    FormCollection fc = Application.OpenForms;
    foreach (Form frm in fc)
    {
        if (frm.Name == "FormBrowseNetworkInformation")
        {
            _open = true;
            frm.Select();
            break;
        }
    }
    if (_open == false)
    {
        var formBrowseNetworkInformation = new FormBrowseNetworkInformation();
        formBrowseNetworkInformation.Show();
    }
}

Solution 24 - C#

this will word definitely. i use this function for myself as well.

  public static bool isFormOpen(Form formm)
    {
       
        foreach (Form OpenForm in Application.OpenForms)
        {
            if (OpenForm.Name == formm.Name)
            {
                return true;
            }
        }

        return false;
    }

Solution 25 - C#

I've tweaked an earlier post I made. This work flawlessly without having to iterate though all open forms.

        Form fc = Application.OpenForms["FormBrowse"];
        if (fc != null)
        {
            fc.Select();
        }
        else
        {
            var formBrowse = new FormBrowse();
            formBrowse.Show();
        }

Solution 26 - C#

This works if you want to Check if the Second Form is already Open and avoidt opening it again on buttong Click.

 int formcheck = 0;
    private void button_click()
    {
       Form2Name myForm2 = new Form2Name();
       if(formcheck == 0)
       {
          myForm2.Show(); //Open Form2 only if its not active and formcheck == 0
          // Do Somethin

          formcheck = 1; //Set it to 1 indicating that Form2 have been opened
       {   
    {

Solution 27 - C#

You can use ShowDialog() instead of using Show()

Something like this:

var newView = (viewForm)Program.ServiceProvider.GetService(typeof(viewForm));
 newView.ShowDialog();

Solution 28 - C#

In addition, may be this will help


class Helper
{
public void disableMultiWindow(Form MdiParent, string formName)
{
FormCollection fc = Application.OpenForms;
try
{
foreach (Form form in Application.OpenForms)
{
if (form.Name == formName)
{
form.BringToFront();
return;
}
}



            Assembly thisAssembly = Assembly.GetExecutingAssembly();
            Type typeToCreate = thisAssembly.GetTypes().Where(t => t.Name == formName).First();
            Form myProgram = (Form)Activator.CreateInstance(typeToCreate);
            myProgram.MdiParent = MdiParent;
            myProgram.Show();
        }
        catch (Exception ex) { MessageBox.Show(ex.Message); }
    }
}





Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionData-BaseView Question on Stackoverflow
Solution 1 - C#SaschaView Answer on Stackoverflow
Solution 2 - C#SeshagiriView Answer on Stackoverflow
Solution 3 - C#Praveen VRView Answer on Stackoverflow
Solution 4 - C#default localeView Answer on Stackoverflow
Solution 5 - C#Kashif FarazView Answer on Stackoverflow
Solution 6 - C#FarhadMohseniView Answer on Stackoverflow
Solution 7 - C#Hengki LodwigView Answer on Stackoverflow
Solution 8 - C#NIRANJAN PHANSALKARView Answer on Stackoverflow
Solution 9 - C#Ramgy BorjaView Answer on Stackoverflow
Solution 10 - C#kaMChyView Answer on Stackoverflow
Solution 11 - C#Lithin KuriachanView Answer on Stackoverflow
Solution 12 - C#BeyondoView Answer on Stackoverflow
Solution 13 - C#Sabri GhaithView Answer on Stackoverflow
Solution 14 - C#Jim LahmanView Answer on Stackoverflow
Solution 15 - C#Louie AvilaView Answer on Stackoverflow
Solution 16 - C#naeemshah1View Answer on Stackoverflow
Solution 17 - C#Tanmay NeheteView Answer on Stackoverflow
Solution 18 - C#CastielView Answer on Stackoverflow
Solution 19 - C#LeviteView Answer on Stackoverflow
Solution 20 - C#Ram Prasad JoshiView Answer on Stackoverflow
Solution 21 - C#Deron DilgerView Answer on Stackoverflow
Solution 22 - C#Adrian DinuView Answer on Stackoverflow
Solution 23 - C#user9274088View Answer on Stackoverflow
Solution 24 - C#Sayed Muhammad IdreesView Answer on Stackoverflow
Solution 25 - C#user9274088View Answer on Stackoverflow
Solution 26 - C#ChadView Answer on Stackoverflow
Solution 27 - C#Nestor Alfonso SierraView Answer on Stackoverflow
Solution 28 - C#Slomotion JakartaView Answer on Stackoverflow