janhartmann
janhartmann

Reputation: 15003

Firing application exit on Windows shutdown

I have a winforms program which have an "Exit" button which fires an event that performs a clean up and then afterwards fire Application.Exit(); to exit the program.

But since the program is a tray application, I often forget to shut down the program using this exit button and just hitting the Windows shutdown instead. If I do that the event is not called and therefore not cleaning up.

My question is: Is there an event I can count on when using different closing methods, like windows shutdown?

I have seen I can override OnClosing - but is this the correct way?

Edit:

All answers did work. But I eventually ended out with:

Application.ApplicationExit += new EventHandler(Application_ApplicationExit);

Upvotes: 3

Views: 2498

Answers (2)

Marco
Marco

Reputation: 57593

I think you could use this:

void Init()
{
    SystemEvents.SessionEnding += 
        new SessionEndingEventHandler(SystemEvents_SessionEnding);
}

void SystemEvents_SessionEnding(object sender, SessionEndingEventArgs e)
{
    // Do what you need
}

A gool link to read could be this

EDITED: This solutions works even in a non form application (console, service, etc...).

Upvotes: 4

Yes, to find different closing methods overriding the OnClosing event will work. Look at the below code part.

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            try
            {
                ConfirmClose = true;
                base.OnFormClosing(e);
                if (e.CloseReason == CloseReason.WindowsShutDown)
               {
                    //Do some action
               }
            }
          }
            catch (Exception ex)
            {

            }
        }

Upvotes: 3

Related Questions