Reputation: 523
I created a window that can be closed only when you click outside of it. The code works very well here:
protected override void OnDeactivated(EventArgs e)
{
try
{
base.OnDeactivated(e);
Close();
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
}
The only problem comes when the window is closed, for example, with alt + f4
, in particular, takes this exception:
You can not set Visibility to Visible or call Show, ShowDialog, Close WindowInteropHelper.EnsureHandle or while you are on the closure of the Window.
How can I make sure to avoid it? Actually I've managed the exception with Try/Catch..
Upvotes: 3
Views: 1111
Reputation: 4298
Before the window's Deactivated
event is raised, the Closing
event occurs (but, obviously, only if the window is closed on purpose by the user, e.g. by pressing Alt+F4
). This means you can set a flag in the window's Closing
event handler indicating that the window is currently being closed, meaning that the Close()
method needs not be called in the Deactivated
event handler:
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();
}
Upvotes: 3