tags:

views:

44

answers:

3

How do I run some clean up code when a user closes a window?

+5  A: 

Subscribe to FormClosing event.

Giorgi
+3  A: 

You can hook up to the Closing event on your window (if you are using WPF).

klausbyskov
The event is actually called `FormClosing` to be accurate ;)
Øyvind Bråthen
@Øyvind Bråthen, not in WPF. Check the link for yourself ;-)
klausbyskov
@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
@Øyvind Bråthen, hehe thanks. But I don't think *I* got you. You got yourself ;-)
klausbyskov
A: 

Put your clean up code in the destructor.

public MyClass
{
  public MyClass()
  {
     // initialse class
  }
  ~MyClass()
  {
     // cleanup class
  }
}
Dave Anderson
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
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