C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: This is also a good place to put some initialization code. These run before the form is displayed.
FormClosing: Here you can use logic to see if the program should stay open. Perhaps some data was not saved to the database.
Cancel: Set the Cancel property on the FormClosingEventArgs to true and the Form will remain open. A dialog box might be helpful.
MessageBoxFormClosed: Here you know the Form has been closed. You can't cancel it at this point. This is a good place to write settings to the disk.
Settings.settingsC# program that uses Load, FormClosing, FormClosed
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// You can set properties in the Load event handler.
this.Text = DateTime.Now.DayOfWeek.ToString();
this.Top = 60;
this.Left = 60;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// You can cancel the Form from closing.
if ((DateTime.Now.Minute % 2) == 1)
{
this.Text = "Can't close on odd minute";
e.Cancel = true;
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
// You can write to a file to store settings here.
}
}
}
However: If you are handling child forms, it is probably best to reference them through the most derived type.
And: This will create the following method, which we have also added the using statement to.
Info: We see the Click event handler for button4, which is just a regular Button control in Windows Forms.
Parameters: The 2 parameters, "object sender" and "EventArgs e" are not specific to this example and you can ignore them.
ButtonMethod that demonstrates using keyword on Form: C#
private void button4_Click(object sender, EventArgs e)
{
using (Form2 form2 = new Form2())
{
form2.ShowDialog();
}
}
Also: ShowDialog is called on the new Form instance. This will show the dialog in the form. You can assign its result to a DialogResult.
DialogResultSo: No matter what happens in ShowDialog, the Form instance will be properly disposed.
UsingVersion that passes argument to Form: C#
private void button1_Click(object sender, EventArgs e)
{
using (Form3 form3 = new Form3(new object())) // <-- Parameter
{
DialogResult result = form3.ShowDialog();
if (result == DialogResult.OK) // <-- Checks DialogResult
{
}
}
}