PRENDETEVELO NEL CULO
PRENDETEVELO NEL CULO

Reputation: 133

Cannot call specific method on closing

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?

Upvotes: 0

Views: 640

Answers (3)

Patrick Artner
Patrick Artner

Reputation: 51643

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.

Upvotes: 0

Jorge Y.
Jorge Y.

Reputation: 1133

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()

Upvotes: 1

RMH
RMH

Reputation: 837

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

}

Upvotes: 2

Related Questions