0
votes

I have a window where I need to fire a specific method when this window closing, I did:

public FooWindow()
{
   Closing += (x, y) => Exit();
}

private void Exit()
{
   if (someVariable)
   {
       Environment.Exit(1);
   }
   else
   {
      Close(); 
   }

}

when the Exit event is called the close method is reached but I get

System.InvalidOperationException: Cannot set Visibility or call Show, ShowDialog, or WindowInteropHelper.EnsureHandle after a Window has closed.

what am i doing wrong?

3
I don“t see any code that sets the visibility or calls Show. Anyway why do you exit the app on closing? Wouldnt this hapen anyway? Or is your form called from another one? In thie latter case you shpuld close the parent window, not the program. - HimBromBeere
because I use the exit method also in another method, so I cannot close the app in the closing event but I need to call exit - PRENDETEVELO NEL CULO

3 Answers

1
votes

Seems you are calling Close(); when the Closing event is called. Which sounds to me that you are trying to close a window that is already in the process of closing itself.

That said, if you still want the Exit() method to close if your someVariable is false. Track the 'closing' status of your form with a boolean, something like the following:

private bool _isClosing = false;
public FooWindow()
{
   Closing += (x, y) => {
       _isClosing = true;
       Exit(); 
   };
}

private void Exit()
{
   if (someVariable)
   {
       Environment.Exit(1);
   }
   else
   {
      if (!_isClosing) Close(); 
   }

}
1
votes

The problem is that you are calling Close() while the window is already closing. So WPF checks for that scenario and launches you the exception to notice the error. Here the call stack I got reproducing your problem. See that the code launching the exception has a self evident name VerifyNotClosing:

   in System.Windows.Window.VerifyNotClosing()
   in System.Windows.Window.InternalClose(Boolean shutdown, Boolean ignoreCancel)
   in System.Windows.Window.Close()
   in WpfApp1.MainWindow.MainWindow_Closing(Object sender, CancelEventArgs e) in MainWindow.xaml.cs:line 32
   in System.Windows.Window.OnClosing(CancelEventArgs e)
   in System.Windows.Window.WmClose()
0
votes

Window.Close() calls InternalClose() which calls VerifyNotClosing() which throws:

private void VerifyNotClosing()
{
     if (_isClosing == true)
     {
          throw new InvalidOperationException(SR.Get(SRID.InvalidOperationDuringClosing));
     }

     if (IsSourceWindowNull == false && IsCompositionTargetInvalid == true)
     {
          throw new InvalidOperationException(SR.Get(SRID.InvalidCompositionTarget));
     }
}

_isClosing is set to true by InternalClose() on your first visit. SR.Get(SRID.InvalidCompositionTarget) is the error message you see.