Search code examples
c#eventsclass-librarysubscriptionapplication-shutdown

How to subscribe to application shutdown event in class library


There is a class library used by some application. It contains a class A for external usage with a static field of another private class B inside the library. User application uses instances of class A from the library.

As the application shutdowns I'd like to perform some clean up in class B. Is it possible to catch application shutdown event in class B without any action from user application?

class B
{
    public B()
    {
        // attach Handler() to applicaiton shutdown event
    }

    void Handler()
    {
        // do some work
    }
}

Solution

  • using System.Windows.Forms;
    
    public class B
    {
        public B()
        {
            Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
        }
    
        void Application_ApplicationExit(object sender, EventArgs e)
        {
            //do cleanup of your class
        }
    }