c# - 检查窗口是否真正关闭的更好方法

标签 c# wpf windows

我想知道是否有比以下方法更好的方法来检查窗口是否关闭,或者 Closing 是否取消了关闭过程?

我们按我的方式走:

var window = Application.Current.Windows.FirstOrDefault(x => x is FooWindow);
if (window != null)
{
    var gotClosed = false;
    window.Closed += (sender, args) => gotClosed = true;
    window.Close();
    if (gotClosed == false)
    {
        //Close got cancled, by closing...
    }
}

最佳答案

通过检查 .NET 源代码,我不太确定 IsDisposed 是否安全。虽然似乎没有很多安全的选择。到目前为止,我一直使用的没有问题的方法是在关闭后检查 Visibility 属性的 Visible

更简洁的方法可能是创建您自己的类并重写 OnClosing()OnClosed():

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
    // Fires Closing event
    base.OnClosing(e);

    if (!e.Cancel)
    {
        // Window was allowed to close.
        // Set IsClosed = true or something like that
    }
}

例如,您可以将结果存储在一个属性中。

关于c# - 检查窗口是否真正关闭的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22866911/

相关文章:

windows - 如何为我的 .inf 创建 Windows 安装包?

c# - 调用 .DLL 的 NUnit 测试调用 WCF Web 服务 (.NET C#)

c# - 函数重载

c# - 检查类中是否存在属性

c# - Wpf动画背景颜色

c# - 全局捕获后台线程中 WCF 异步调用引发的异常

c++ - 使用 "::"字符串名称在 C++ 中调用 DLL 导出

c# - 创建位图时的相对路径

c# - 一旦第二个窗口关闭,属性就会恢复为原始值

c++ - 在 x86 上如何将 double 传递给函数