How can I execute some code when the user closes the application?

Where do I put this code?

Recommended Answers

All 4 Replies

Depending on what you need to do, you put it in the FormClosing or FormClosed event.

How can this be done?

What about the Application.Exit() function?

I am looking to execute some code when the user presses the 'x' at the top right of the screen

How can this be done?

What about the Application.Exit() function?

I am looking to execute some code when the user presses the 'x' at the top right of the screen

private void form1_FormClosing( object sender , FormClosingEventArgs e )
{
       //code
}

Dont forget to attach the event handler. This should go into your Form1.designer.cs

this.FormClosing += new System.Windows.Forms.FormClosingEventHandler( this.Watcher_FormClosing );

EDIT: Yes,this will affect any maner you try to exit the application.

Thanks, it was the designer.cs file I was having trouble with but it works great now!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.