如何检查 WPF 窗口打开或关闭

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21038615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 10:28:54  来源:igfitidea点击:

How to check WPF window open or close

c#wpfwpf-controlswpf-4.0

提问by EBS

I want to check if some window is opened or closed. If the window is already open focus it. if the window is already close, open the window.

我想检查某个窗口是打开还是关闭。如果窗口已经打开就聚焦它。如果窗户已经关闭,请打开窗户。

I use this code:

我使用这个代码:

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

Can you help with this?

你能帮忙解决这个问题吗?

回答by Lifeless

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