简体   繁体   中英

How to check if window is opened and close it

I am working on C# winforms .

I have function Validate() which is present in the CS file. When I call function Validate() it opens ErrorForm using

ErrorForm ew = new ErrorForm(Errors); // Errors is list<string>
ew.Show();

But when I call it again, a new window opens and my previous window is open too. I have to close that window manually.

Is there any method available such that if I call validate() again, it will close the current ErrorForm and will open new ErrorForm .

Try something like this, a pseudocode ..

public class MyClass 
{
    ErrorForm ew = null; 

    public void Validate() 
    {
       if(ew !=null && !ew.IsDisposed) 
          ew.Close(); 

       ew =  new ErrorForm(Errors);
       ew.Show();
    }
}

您可以使用以下作为静态属性访问的集合: Application.OpenForms

Simplest solution is calling ew.ShowDialog(this) which keeps the ErrorForm on top of your main form.

If you really want to call Form.Show() method, you could implement Singleton pattern in ErrorForm and call GetInstance. In the GetInstance method you can close it or reuse it.

public class ErrorForm 
{
   private static ErrorForm instance;

   private ErrorForm() {}

   public static Singleton GetInstance()
   {
      if (instance == null)
      {
         instance = new ErrorForm();
      }
      else //OR Reuse it
      {
          instance.Close(); 
          instance = new ErrorForm();
      }
      return instance;      
   }

   public Errors ErrorMessages
   {
      set {...}
   }
}

In the validate method

public void Validate() 
    {
       ErrorForm ef = ErrorForm.GetInstance();
       ef.ErrorMessages = errors;
       ef.Show();

    }

try this one:

var f1=Application.OpenForms["ErrorForm"];       
if(f1!=null) 
  f1.Close(); 

f1=  new ErrorForm(Errors);
f1.Show();

您可以使用ShowDialog()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM