dimanche 13 avril 2014

c# - meilleure façon de vérifier si la fenêtre a obtenu effectivement fermé - Stack Overflow


I would like to know if there is a better way than the following to check if the window got closed, or if a Closing cancled the closing procedure?


Here we go with my way:


var window = Application.Current.Windows.FirstOrDefault(x => x is FooWindow);
if (window != null)
{
var gotClosed = false;
window.Closed += (sender, args) => gotClosed = true;
window.Close();
if (gotClosed == false)
{
//Close got cancled, by closing...
}
}



I'm not sure it's better than your solution, but after calling window.Close() the property IsDisposed gets true. So, you can check it:


if(window.IsDisposed) { .... }




From checking the .NET source, I'm not too sure that IsDisposed is safe. There don't seem to be a lot of safe options though. The one I have been using so far without issues is checking the Visibility property for Visible after closing.


A cleaner approach might be creating your own class and overriding OnClosing() or OnClosed() though:


protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
// Fires Closing event
base.OnClosing(e);

if (!e.Cancel)
{
// Window was allowed to close.
// Set IsClosed = true or something like that
}
}

There you can store the result in a property for example.



I would like to know if there is a better way than the following to check if the window got closed, or if a Closing cancled the closing procedure?


Here we go with my way:


var window = Application.Current.Windows.FirstOrDefault(x => x is FooWindow);
if (window != null)
{
var gotClosed = false;
window.Closed += (sender, args) => gotClosed = true;
window.Close();
if (gotClosed == false)
{
//Close got cancled, by closing...
}
}


I'm not sure it's better than your solution, but after calling window.Close() the property IsDisposed gets true. So, you can check it:


if(window.IsDisposed) { .... }



From checking the .NET source, I'm not too sure that IsDisposed is safe. There don't seem to be a lot of safe options though. The one I have been using so far without issues is checking the Visibility property for Visible after closing.


A cleaner approach might be creating your own class and overriding OnClosing() or OnClosed() though:


protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
// Fires Closing event
base.OnClosing(e);

if (!e.Cancel)
{
// Window was allowed to close.
// Set IsClosed = true or something like that
}
}

There you can store the result in a property for example.


Related Posts:

0 commentaires:

Enregistrer un commentaire