xizor
asked on
Run code on exit of program
I'm new to C# i've only just started playing around with it this week so i'm not very good.
I've been searching around and haven't found the solution I'm looking for yet.
In VB6 I used to use Form_Unload event to run some code when closing a form.
I can not work out how to do this in C#. I have my project so far that says "Hello" in a messsage box (as pasted in code sample)
using the code
MessageBox.Show("Bye", "Farewell", MessageBoxButtons.OK, MessageBoxIcon.Exclamation );
Where and how do I put this into the code to run when the program closes. I want this to run when I:
* Press X on the title bar to close the program
* Press close from the system menu (Alt+F4)
Thanks.
I've been searching around and haven't found the solution I'm looking for yet.
In VB6 I used to use Form_Unload event to run some code when closing a form.
I can not work out how to do this in C#. I have my project so far that says "Hello" in a messsage box (as pasted in code sample)
using the code
MessageBox.Show("Bye", "Farewell", MessageBoxButtons.OK, MessageBoxIcon.Exclamation
Where and how do I put this into the code to run when the program closes. I want this to run when I:
* Press X on the title bar to close the program
* Press close from the system menu (Alt+F4)
Thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Test1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("Hello", "Welcome", MessageBoxButtons.OK, MessageBoxIcon.Exclamation );
}
}
}
Form1_FormClosing
ASKER
but how do I use it?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
As above FormClosing event will handle this for you. However its draw back is that if you close a child form, then it will just handle that form closing (unless you specifically call Application.Exit()) So if you use child forms make sure your application closing code is in the parent. And example is:
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
// This event is automatically fired when you try to close the form
// Here is two methods to handle different closing styles:
if (e.CloseReason == CloseReason.ApplicationExitCall) // If you click "X"
{
// Your code to handle clicking X
}
else
{
// Your code to handle closing via other methods.
}
}
ASKER
Thankyou!