سؤال

When the application receives a call from the service, it opens a form for each call. The user must make his input in each window and the close it. In order to smooth the user's work I am trying to reactivate the window the user was working on when the next one is being shown.

The method for doing this is below:

private void ActivatePreviousActiveForm() {

    if (_activeWhenOpen != null && _activeWhenOpen.InvokeRequired) {
         if (!_activeWhenOpen.Disposing || !_activeWhenOpen.IsDisposed)
              _activeWhenOpen.Invoke((MethodInvoker)ActivatePreviousActiveForm);
    } else
         if (_activeWhenOpen != null && !(_activeWhenOpen is FrmRuntimeError))
             _activeWhenOpen.Activate();
}

Sometime it throws ""Cannot access a disposed object" when reaching the line

if (!_activeWhenOpen.Disposing || !_activeWhenOpen.IsDisposed)

Does anyone know why this would happen?

هل كانت مفيدة؟

المحلول

Try to invert the if condition:

This line

if (!_activeWhenOpen.Disposing || !_activeWhenOpen.IsDisposed)

has to become

if (!_activeWhenOpen.IsDisposed || !_activeWhenOpen.Disposing)

That is because the condition are checked in the order they are written, so your code may call Disposing on an object that is alredy disposed, raising your error.

EDIT:

I also think that you should change the || to a && , because if your window is not Disposed but is in Disposing status, you may have an error.

نصائح أخرى

You cannot access a disposed object. Why is it disposed? When the user closes the form, the default behavior of closing is to dispose it. In order to prevent that, you'll have to override the Close method so it just hides the form instead of dispose it. Like this:

// Use this event handler for the FormClosing event.
private void YourFormClosing(object sender, FormClosingEventArgs e)
{
  this.Hide();
  e.Cancel = true; // this will cancel the close event.
}

Regards.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top