There are two ways to go about this whole thing.
The first way is the one I like best because it is symmetrical (you
can, if you wish have form1 listening for event A from form2 and form2
listening for event B from form1, if you ever need to do that) and
because it fits nicely into a design pattern called
MVC--model-view-controller--brought to us by our friends in the Java
community.
All you have to do is make a property or a method of your form that is
going to be listening. Use a property if the listening form already
knows which event it wants to listen to. You'll need to use a method
and Reflection if you want to specify the name of the event at run
time. I'll use a property here because it's more common, and simpler:
public class Form2 : Form
{
Form1 otherForm = null;
....
public Form1 OtherForm
{
get { return this.otherForm; }
set
{
if (this.otherForm != null) { this.otherForm.theEvent -=
new EventHandler(this.handleForm1Event); }
this.otherForm = value;
if (this.otherForm != null) { this.otherForm.theEvent +=
new EventHandler(this.handleForm1Event); }
}
}
private void handleForm1Event(object sender, System.EventArgs e)
{
....
}
}
The second way is to pass a reference to Form1 to Form2's constructor
as you mentioned. This presumes that Form2 will always be listening to
the same Form1 for the duration of its existence (until another Form2
is created using "new", at which point you can pass a different Form1
to that new instance). This is less flexible, but it will still work:
public class Form2 : Form
{
public Form2(Form1 otherForm)
{
otherForm.theEvent += new EventHandler(this.handleForm1Event);
}
private void handleForm1Event(object sender, System.EventArgs e)
{
....
}
}
As I said, I prefer the first method, because it allows you to change
which Form1 the Form2 is listening to.
In both of these cases I've been a bit sloppy: when the form closes you
really ought to remove the listener from the other form's event
handler, or the garbage collector will not clean up the memory used by
Form2 until Form1 is ready to be garbage collected, too. However,
that's a bit esoteric and nothing to worry about in a simple
application.