How do I know if a WPF window is opened

前端 未结 9 1852
天命终不由人
天命终不由人 2020-12-04 19:21

In a WPF window, how do I know if it is opened?

My goal to open only 1 instance of the window at the time.

So, my pseudo code in the parent window is:

<
相关标签:
9条回答
  • 2020-12-04 20:03

    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
       {   
    {
    
    0 讨论(0)
  • 2020-12-04 20:07

    Here is another way to achieve this using LINQ.

    using System.Linq;
    
    ...
    
    public static bool IsOpen(this Window window)
    {
        return Application.Current.Windows.Cast<Window>().Any(x => x == window);
    }
    

    Usage:

    bool isOpen = myWindow.IsOpen();
    
    0 讨论(0)
  • 2020-12-04 20:13
    public bool IsWindowOpen<T>(string name = "") where T : Window
    {
        return Application.Current.Windows.OfType<T>().Any(w => w.GetType().Name.Equals(name));               
    }
    
    0 讨论(0)
提交回复
热议问题