我创建了一个窗口,只有当你点击它外面的时候它才能关闭。该代码在这里运行良好:
protected override void OnDeactivated(EventArgs e)
{
try
{
base.OnDeactivated(e);
Close();
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
}
唯一的问题出现在窗口关闭时,例如,使用 alt + f4
,特别是会出现以下异常:
You can not set Visibility to Visible or call Show, ShowDialog, Close WindowInteropHelper.EnsureHandle or while you are on the closure of the Window.
我怎样才能确保避免它?实际上,我已经使用 Try/Catch 处理了异常。
最佳答案
在窗口的 Deactivated
事件被引发之前,Closing
事件发生(但是,很明显,只有当用户故意关闭窗口时,例如通过按 Alt+F4
)。这意味着您可以在窗口的 Closing
事件处理程序中设置一个标志,指示窗口当前正在关闭,这意味着 Close()
方法不需要在 Deactivated
事件处理程序:
private bool _isClosing;
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
_isClosing = true;
}
protected override void OnDeactivated(EventArgs e)
{
base.OnDeactivated(e);
if (!_isClosing)
Close();
}
关于c# - 系统.InvalidOperationException : Can not set Visibility,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32421731/