Event handling (consuming) between forms

How to handle event:

objEditClassForm = new EditClass();
objEditClassForm.FormClosed += new FormClosedEventHandler(this.EditClassForm_Closed);

To explain in details:

objEditClassForm => is an object of the class EditClass (which inherits from the Form class)

So, in short, “objEditClassForm” is a simple windows form!
FormClosed => is a property of the class EditForm, this property is an “event” property

It is defined as follows:

public event FormClosedEventHandler FormClosed;

– This is code is defined in the System.Windows.Forms.Form class (built-in in Visual Studio)
– We can see that the property is declared as event
– We can also see that they type of the event is pre-defined (FormClosedEventHandler)

it is also built-in in Visual Studio in System.Windows.Forms.FormClosedEventHandler file, and is simply defined as:

public delegate void FormClosedEventHandler(object sender, FormClosedEventArgs e);

We can see that defining an event can be extremely simple!!!

+= sign => it is a necessary syntax when defining an event handler for the event

FormClosedEventHandler => see above

this.EditClassForm_Closed => is a function that will handle our event

In my example, it looks as follows:

private void EditClassForm_Closed(object sender, EventArgs e){
_load_all();
}

NOTES:

If you close (dispose of) the class that was assigned an event handler, it will not contain the event handler after that.

You will have to do it again!!!

Another example from MSDN is here:

using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Drawing;

public class MyForm : Form
{
private TextBox box;
private Button button;
public MyForm() : base()
{
box = new TextBox();
box.BackColor = System.Drawing.Color.Cyan;
box.Size = new Size(100,100);
box.Location = new Point(50,50);
box.Text = “Hello”;
button = new Button();
button.Location = new Point(50,100);
button.Text = “Click Me”;

// To wire the event, create
// a delegate instance and add it to the Click event.
button.Click += new EventHandler(this.Button_Clicked);
Controls.Add(box);
Controls.Add(button);
}

// The event handler.
private void Button_Clicked(object sender, EventArgs e)
{
box.BackColor = System.Drawing.Color.Green;
}

// The STAThreadAttribute indicates that Windows Forms uses the
// single-threaded apartment model.
[STAThreadAttribute]
public static void Main(string[] args)
{
Application.Run(new MyForm());
}

}

Leave a comment