2014-01-10 118 views
1

我想檢查是否打開或關閉一些窗口。如果窗口已經打開重點是。如果窗口已經關閉,請打開窗口。如何檢查WPF窗口打開或關閉

我用這個代碼:

public static bool IsWindowOpen<T>(string name = "") where T : Window 
{ 
    return string.IsNullOrEmpty(name)? Application.Current.Windows.OfType<T>().Any(): Application.Current.Windows.OfType<T>().Any(w => w.Name.Equals(name)); 
} 

private void MenuItem1_OnClick(object sender, RoutedEventArgs e) 
{ 
    if (IsWindowOpen<Window>("TestForm")) return; 
    var window1 = new Window1 { Name = "TestForm", Title = "Welcome", }; 
    window1.Show(); 
} 

你能有幫助呢?

+0

你從來沒有說過什麼問題 –

+1

也許你可以改變「我使用此代碼」到「我使用此代碼,但是......」 =) –

+0

我不會來,如果窗口是打開該窗口焦點 – EBS

回答

5
public static T IsWindowOpen<T>(string name = null) 
    where T : Window 
{ 
    var windows = Application.Current.Windows.OfType<T>(); 
    return string.IsNullOrEmpty(name) ? windows.FirstOrDefault() : windows.FirstOrDefault(w => w.Name.Equals(name)); 
} 

private void MenuItem1_OnClick(object sender, RoutedEventArgs e) 
{ 
    var window = IsWindowOpen<Window>("TestForm"); 

    if (window != null) 
    { 
     window.Focus(); 
    } 
    else 
    { 
     window = new Window1 { Name = "TestForm", Title = "Welcome", }; 
     window1.Show(); 
    } 
}