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

 

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

  e.Cancel = true;

  //继续执行别的代码:

  ......

  ......

  var window = sender as Window;

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

参考连接

上一篇:7-13 日K蜡烛图


下一篇:量化投资之工具篇一:Backtrader从入门到精通(1)