在 Window 关闭时,无法将 Visibility 设置为 Visible,也无法调用 Show、ShowDialog、Close 或 WindowInteropHelper.EnsureHandle。

 bool isForce = false;

private static async void Window_Closing(object sender, CancelEventArgs e)
{

  if(!isForce)

  {

    e.Cancel = true;

    //继续执行别的代码:

    ......

    ......

    var window = sender as Window;

    isForce = true;

    window.ForceClose();

  }

}

/// <summary>
/// 强制关闭窗体
/// <para>在Window的Closing事件执行Close会报如下错误:</para>
/// <para>Cannot set Visibility to Visible or call Show, ShowDialog, Close, or WindowInteropHelper.EnsureHandle while a Window is closing.</para>
/// <para>使用此方法可解决问题并成功关闭窗体</para>
/// </summary>
/// <param name="window"></param>
public static async void ForceClose(this Window window)
{
  await Dispatcher.CurrentDispatcher.InvokeAsync(() => window.Close(), DispatcherPriority.Normal);
}

参考连接

posted @ 2021-08-12 11:52  苏秦与真相  阅读(1393)  评论(0编辑  收藏  举报