Form. Every Windows Forms program will use the Form class. In many programs, the Load, FormClosing and FormClosed event handlers provide needed functionality.
Intro notes. We look closer at Form. We demonstrate several event handlers on the Form class. Many other properties and event handlers are available.
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.
Detail In Form1_Load, you can set things like the title text (Text property) or the Window position.
Detail Here you can use logic to see if the program should stay open. Perhaps some data was not saved to the database.
Detail Set the Cancel property on the FormClosingEventArgs to true and the Form will remain open. A dialog box might be helpful.
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.
}
}
}
Using. The clearest way to create a new Form is to add the using statement to your code and then call Show or ShowDialog. Please add a button_Click event handler to a button.
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
{
}
}
}
Base. Form 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.
Summary. The Form type presents several important event handlers as well as properties. The Load, FormClosing, and FormClosed event handlers are of particular interest.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 24, 2022 (simplify).