In a WPF application there is a small information form that is called from the main one. As planned, this informational form should have a standard cross for closing, and the form should also close itself when the focus is lost. I use for this Window_Deactivated.

private void Window_Deactivated(object sender, EventArgs e) { this.Close(); } 

If the focus is lost, everything works as it should, but when you close the form through a cross, an exception occurs:

System.InvalidOperationException: 'While closing a window, you cannot set Visibility to Visible or call Show, ShowDialog, Close or WindowInteropHelper.EnsureHandle.'

Is it possible to somehow catch in Deactivated that the form is already closed, so as not to throw a re-closure and not to cause an exception?

  • Add a flag to Window_Closing to ignore the Window_Deactivated event. Or, if Window_Deactivated occurs before Window_Closing make a custom button in the handler of which set a flan to prohibit the operation of the code from the Window_Deactivated event. - Rootware

1 answer 1

Yes you can, set the flag and check it:

 bool isClosing = false; protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); isClosing = true; // Возможно, правильнее isClosing = !e.Cancel; // если выдаете запрос на закрытие или что-то типа того } private void Window_Deactivated(object sender, EventArgs e) { if (!isClosing) Close(); } 
  • one
    Thank you, with attempts to study a bunch of sophisticated patterns, such simple thoughts completely stop coming. The only thing that in WPF in Window_Closing cannot be caused base - to leave in a recursion. Just set the flag - then everything works as it should. - Good Irbis
  • Well, I do not have a subscriber to the Window_Closing event, but an overload of the base class method (see the same override ). But in general, you can, of course, do as you wrote :) - Andrew NOP