gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:39:57 25 4
gpt4 key购买 nike

我想检查某个窗口是否打开或关闭。如果窗口已经打开,请关注它。如果窗口已经关闭,请打开窗口。

我使用这段代码:

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

你能帮忙吗?

最佳答案

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

关于c# - 如何检查 WPF 窗口打开或关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21038615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com