How do I run some clean up code when a user closes a window?
+3
A:
You can hook up to the Closing
event on your window (if you are using WPF).
klausbyskov
2010-10-25 11:52:51
The event is actually called `FormClosing` to be accurate ;)
Øyvind Bråthen
2010-10-25 11:55:10
@Øyvind Bråthen, not in WPF. Check the link for yourself ;-)
klausbyskov
2010-10-25 11:56:57
@Klaus - Since the OP didn't state WPF or not, I will have to say *touché*. You got me there. I'll even throw in a +1 for good measure. ;)
Øyvind Bråthen
2010-10-25 14:54:27
@Øyvind Bråthen, hehe thanks. But I don't think *I* got you. You got yourself ;-)
klausbyskov
2010-10-25 14:57:22
A:
Put your clean up code in the destructor.
public MyClass
{
public MyClass()
{
// initialse class
}
~MyClass()
{
// cleanup class
}
}
Dave Anderson
2010-10-25 11:56:57
A window closing is not the same as the class being destructed. The window can be closed, but a reference to it may still be held by the program.
klausbyskov
2010-10-25 12:00:16
From: http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx *However, when your application encapsulates unmanaged resources such as windows, files, and network connections, you should use destructors to free those resources.*
Dave Anderson
2010-10-25 22:33:58