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

Where do I put this code?

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.