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