TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Form: Event Handlers

This C# tutorial shows how to use the Form type in Windows Forms.

Form. Every Windows Forms program will use the Form class. In many programs,

the Load, FormClosing and FormClosed event handlers provide needed functionality. We look closer at Form. We demonstrate several event handlers on the Form class.

Load. To start, create a new Windows Forms program. Next, we add the Load event handler. In Visual Studio, double-click somewhere on the visible Form. In Form1_Load, you can set things like the title text (Text property) or the Window position.

Tip: This is also a good place to put some initialization code. These run before the form is displayed.

C# 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.
	}
    }
}

FormClosing event handler. It's sad to think anyone would want to close your program, but this will happen. In FormClosing, you can use logic to see if the program should stay open. Perhaps some data was not saved to the database.

Tip: Set the Cancel property on the FormClosingEventArgs to true and the Form will remain open. A dialog box might be helpful.

MessageBox.Show

 

In FormClosed, 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 or perform logic that affects the state of the system after the Form or entire program terminates.

Settings.settings

Base. The form class is an important one. It is the base class for all custom windows (such as Form1) that you might develop. You can reference all these derived types from the base type Form.

However: If you are handling child forms, it is probably best to reference them through the most derived type.

Using. The clearest way to create a new Form is to add the using statement to your code and then call Show or ShowDialog. To start, you can add a button_Click event handler to your button in Windows Forms by double-clicking on it in the Designer.

And: This will create the following method, which we have also added the using statement to.

Method that demonstrates using keyword on Form: C#

private void button4_Click(object sender, EventArgs e)
{
    using (Form2 form2 = new Form2())
    {
	form2.ShowDialog();
    }
}

We see the Click event handler for button4, which is just a regular Button control in Windows Forms. The two parameters, "object sender" and "EventArgs e" are not specific to this example and you can ignore them.

Button

Using statement. Let's look carefully at how the using statement contains the assignment of a new instance of the Form2 form. The new Form2() constructor is inside the using condition.

Constructor

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.

DialogResult

IDisposable. Form types implement the IDisposable interface, which is a special interface that is called when you have the "using" statement. Windows Forms use system resources that must be cleaned up after you are done with them.

So: No matter what happens in ShowDialog, the Form instance will be properly disposed.

Using

Parameter. Here we see a short example of how you can use DialogResult and ShowDialog together. We also pass a parameter to the Form3 constructor. It is useful to pass parameters to Form constructors. You will need to modify the constructor manually.

Version 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
	{
	}
    }
}

Summary. The Form type presents several important event handlers as well as properties. The Load, FormClosing, and FormClosed event handlers are of particular interest. Most of the properties and other event handlers are not covered here.

But: They can be used in a similar way to those in the example. And custom types that derive from Form can be used.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf